Массив Json для Pojo

Я пытаюсь разобрать следующий ответ массива Json на коллекцию pojos в RestTemplate.

[{
  "client":{
        "id": 6364,
        "name": "7Seven7 Insurance Inc",
        "email": "[email protected]",
        "currency": {"name":"United States of America, Dollars","symbol":"$"},
        "address": "941 Elm Ave. #5 ",
        "city": "Long Beach",
        "province": "CA",
        "zip_code": "90813",
        "country": "United States",
        "full_address_with_comma": "941 Elm Ave. #5, Long Beach, CA, 90813, United States",
        "phone": "562-556-4035",
        "fax":"562-381-7500",
        "custom_field_name": "listed",
        "custom_field_value": "false",
        "created_at": "2010-07-18T00:08:10Z",
        "updated_at": "2010-07-21T11:04:58Z",
      }
},
{
  "client":{
        "id":6365,
        "name": "Affinity",
        "email":"[email protected]",
        "address":"2575 Vista Del Mar ",
        "city":"Ventura",
        "province":"California",
        "zip_code":"93001",
        "country":"United States",
        "full_address_with_comma":"2575 Vista Del Mar, Ventura, California, 93001, United States",
        "phone":"(270) 901-2913",
        "fax":null,
        "currency":{"name":"United States of America, Dollars","symbol":"$"},
        "custom_field_name":null,
        "custom_field_value":null
        "created_at":"2010-07-18T00:08:10Z",
        "updated_at":"2010-07-18T00:08:10Z",
      }
}]

Я создал соответствующий класс Java Pojo

public class Client {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("currency")
private String currency;
@JsonProperty("address")
private String address;
@JsonProperty("city")
private String city;
@JsonProperty("province")
private String province;
@JsonProperty("zip_code")
private String zip_code;
@JsonProperty("country")
private String country;
@JsonProperty("full_address_with_comma")
private String full_address_with_comma;
@JsonProperty("phone")
private String phone;
@JsonProperty("fax")
private String fax;
@JsonProperty("custom_field_name")
private String custom_field_name;
@JsonProperty("custom_field_value")
private String custom_field_value;
@JsonProperty("created_at")
private String created_at;
@JsonProperty("updated_at")
private String updated_at;

public String getId() {
    return id;
}
public void setId(String id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getCurrency() {
    return currency;
}
public void setCurrency(String currency) {
    this.currency = currency;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
public String getCity() {
    return city;
}
public void setCity(String city) {
    this.city = city;
}
public String getProvince() {
    return province;
}
public void setProvince(String province) {
    this.province = province;
}
public String getZip_code() {
    return zip_code;
}
public void setZip_code(String zip_code) {
    this.zip_code = zip_code;
}
public String getCountry() {
    return country;
}
public void setCountry(String country) {
    this.country = country;
}
public String getFull_address_with_comma() {
    return full_address_with_comma;
}
public void setFull_address_with_comma(String full_address_with_comma) {
    this.full_address_with_comma = full_address_with_comma;
}
public String getPhone() {
    return phone;
}
public void setPhone(String phone) {
    this.phone = phone;
}
public String getFax() {
    return fax;
}
public void setFax(String fax) {
    this.fax = fax;
}
public String getCustom_field_name() {
    return custom_field_name;
}
public void setCustom_field_name(String custom_field_name) {
    this.custom_field_name = custom_field_name;
}
public String getCustom_field_value() {
    return custom_field_value;
}
public void setCustom_field_value(String custom_field_value) {
    this.custom_field_value = custom_field_value;
}
public String getCreated_at() {
    return created_at;
}
public void setCreated_at(String created_at) {
    this.created_at = created_at;
}
public String getUpdated_at() {
    return updated_at;
}
public void setUpdated_at(String updated_at) {
    this.updated_at = updated_at;
}

}

Я использую RestTemplate, но у меня есть массив клиентов с пустыми значениями атрибутов.

Client[] clients= restTemplate.getForObject(requestUrl, Client[].class);

person enfany    schedule 16.04.2014    source источник


Ответы (1)


Большинство ваших полей POJO имеют тип String, но ваш JSON имеет значения без двойных кавычек (""). Ваш JSON должен быть следующим, чтобы быть действительным:

[
    {
        "client": {
            "id": "6364",
            "name": "7Seven7 Insurance Inc",
            "email": "[email protected]",
            "currency": {
                "name": "United States of America, Dollars",
                "symbol": "$"
            },
            "address": "941 Elm Ave. #5 ",
            "city": "Long Beach",
            "province": "CA",
            "zip_code": "90813",
            "country": "United States",
            "full_address_with_comma": "941 Elm Ave. #5, Long Beach, CA, 90813, United States",
            "phone": "562-556-4035",
            "fax": "562-381-7500",
            "custom_field_name": "listed",
            "custom_field_value": "false",
            "created_at": "2010-07-18T00:08:10Z",
            "updated_at": "2010-07-21T11:04:58Z"
        }
    },
    {
        "client": {
            "id": "6365",
            "name": "Affinity",
            "email": "[email protected]",
            "address": "2575 Vista Del Mar ",
            "city": "Ventura",
            "province": "California",
            "zip_code": "93001",
            "country": "United States",
            "full_address_with_comma": "2575 Vista Del Mar, Ventura, California, 93001, United States",
            "phone": "(270) 901-2913",
            "fax": "null",
            "currency": {
                "name": "United States of America, Dollars",
                "symbol": "$"
            },
            "custom_field_name": "null",
            "custom_field_value": "null",
            "created_at": "2010-07-18T00:08:10Z",
            "updated_at": "2010-07-18T00:08:10Z"
        }
    }
]

Кроме того, ваш JSON имеет поле email, но ваш Client POJO не имеет поля email, а ваше объявленное поле currency в POJO не является String, это объект с двумя полями, поэтому ваш Client POJO должен быть:

public class Client {

    private String id;
    private String name;
    private String email;
    private Currency currency;
    private String address;
    private String city;
    private String province;
    private String zip_code;
    private String country;
    private String full_address_with_comma;
    private String phone;
    private String fax;
    private String custom_field_name;
    private String custom_field_value;
    private String created_at;
    private String updated_at;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Currency getCurrency() {
        return currency;
    }

    public void setCurrency(Currency currency) {
        this.currency = currency;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getZip_code() {
        return zip_code;
    }

    public void setZip_code(String zip_code) {
        this.zip_code = zip_code;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getFull_address_with_comma() {
        return full_address_with_comma;
    }

    public void setFull_address_with_comma(String full_address_with_comma) {
        this.full_address_with_comma = full_address_with_comma;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getFax() {
        return fax;
    }

    public void setFax(String fax) {
        this.fax = fax;
    }

    public String getCustom_field_name() {
        return custom_field_name;
    }

    public void setCustom_field_name(String custom_field_name) {
        this.custom_field_name = custom_field_name;
    }

    public String getCustom_field_value() {
        return custom_field_value;
    }

    public void setCustom_field_value(String custom_field_value) {
        this.custom_field_value = custom_field_value;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

с новым объектом Currency:

public class Currency {

    private String name;
    private String symbol;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSymbol() {
        return symbol;
    }
    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

}

С другой стороны, вы пытаетесь десериализовать массив объектов Client, но ваш JSON представляет собой массив объектов, где каждый объект содержит объект Client, поэтому вам нужно его обернуть:

public class Cliente {

    private Client client;

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

}

а затем вы можете десериализовать JSON с помощью restTemplate или ObjectMapper.
С restTemplate:

Cliente[] clients= restTemplate.getForObject(requestUrl, Cliente[].class);

С ObjectMapper (у Джексона genericMessageConverter делается точно так же, он использует ObjectMapper следующим образом):

Cliente[] clientes= mapper.readValue(jsonStr, Cliente[].class);

Другое дело, что вам не нужны аннотации @JsonProperty в вашем POJO, если ваши поля JSON имеют одно и то же имя в JSON и в POJO.

person vzamanillo    schedule 16.04.2014
comment
Вместо оболочки Cliente можно не использовать ArrayList‹Client›? - person user2441441; 25.08.2016