簡體   English   中英

無法使用傑克遜API將JSON字符串映射到Java對象

[英]Unable to map json string to java object using jackson API

我正在編寫一個Web服務(服務器+客戶端)。 我可以提供服務,並且返回以下json

{
"cities": {
    "city": [
        {
            "name": "New Delhi",
            "population": "19M",
            "telephonecode": "011"
        },
        {
            "name": "Mumbai",
            "population": "21M",
            "telephonecode": "022"
        },
        {
            "name": "Chennai",
            "population": "10M",
            "telephonecode": "044"
        }
    ]
}

}

我的POJO是

@XmlRootElement(name = "cities")
public class RestFulCities {

List<RestFulCity> restFulCityList;

@XmlElement(name = "city")
public List<RestFulCity> getRestFulCityList() {
    return restFulCityList;
}

public void setRestFulCityList(List<RestFulCity> restFulCityList) {
    this.restFulCityList = restFulCityList;
}
}

@XmlRootElement(name = "city")
public class RestFulCity {
private String name;
private String telephonecode;
private String population;

public RestFulCity(String name, String telephonecode, String population) {
    this.name = name;
    this.telephonecode = telephonecode;
    this.population = population;
}

public RestFulCity(City city) {
    this.name = city.getName();
    this.telephonecode = city.getTelephonecode();
    this.population = city.getPopulation();
}
@XmlElement
public String getName() {
    return name;
}
@XmlElement
public String getTelephonecode() {
    return telephonecode;
}

@XmlElement
public String getPopulation() {
    return population;
}
}

現在,我想編寫一個將這個json映射到我的POJO的客戶端,以便獲得用Java填充的RestFulCities對象

我的客戶代碼如下:

public class Client {

static final String REST_URI = "http://localhost:8080/springrest/rest/";
static final String CITIES = "cities";
public static void main(String[] args) {

    String s = "";

    WebClient plainAddClient = WebClient.create(REST_URI);
    plainAddClient.path(CITIES).accept("application/json");
    s = plainAddClient.get(String.class);
    try {

        RestFulCities citiesObject = new ObjectMapper().readValue(s, RestFulCities.class);

        for(RestFulCity city : citiesObject.getRestFulCityList()) {
            System.out.println("----------START---------");
            System.out.println(city.getName());
            System.out.println(city.getPopulation());
            System.out.println(city.getTelephonecode());
            System.out.println("---------END----------");
        }

    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JsonMappingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 }

但問題是:我收到以下異常

org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "cities"(Class com.techartifact.example.spring.model.RestFulCities), not marked as ignorable
 at [Source: java.io.StringReader@1d35bf2; line: 1, column: 12] (through reference    chain: com.techartifact.example.spring.model.RestFulCities["cities"])

當我使用以下屬性時:

@JsonIgnoreProperties(ignoreUnknown = true)

雖然我沒有得到異常,但是我的restFulCityList為null這是不需要的

請幫忙

您正在使用JAXB批注,因此需要使用正確的模塊正確配置ObjectMapper 您需要jackson-module-jaxb-annotations項目。 使用您最喜歡的依賴項管理系統添加它,並像這樣使用它:

JaxbAnnotationModule module = new JaxbAnnotationModule();
// configure as necessary
objectMapper.registerModule(module);

注意:這適用於Jackson2.x。 Jackson 1.x默認情況下支持JAXB,但是該版本不再受支持,並且鑒於您遇到此問題,您可能仍在使用Jackson2.x。

更新: JAXB注釋非常適合與XML系統互操作,但是如果可以的話,您應該真正使用Jackson自己的注釋。 這樣就不需要jaxb模塊和ObjectMapper的配置了。 另外,Jackson中有些功能只能通過其注釋使用,因為JAXB中沒有等效功能。

找到了解決方案。

使用以下代碼:

 JSONObject primary_contact = new JSONObject(s);
 String s1 = primary_contact.getString("cities");
 JSONObject primary_contact1 = new JSONObject(s1);
 String s2 = primary_contact1.getString("city");


 List<City> citiesList = new ObjectMapper().readValue(s2, new TypeReference<List<City>>() { });

客戶代碼應為:

public class Client {

    static final String REST_URI = "http://localhost:8080/springrest/rest/";
    static final String CITIES = "cities";
    static final String CITIES_BHUVAN = "cities/bhuvan";
    static final String BHUVAN = "bhuvan";
    static final String BHUVAN_BHUVAN = "bhuvan/bhuvan";

    public static void main(String[] args) throws JSONException {

        String s = "";

        WebClient plainAddClient = WebClient.create(REST_URI);
        plainAddClient.path(CITIES).accept("application/json");
        s = plainAddClient.get(String.class);
        try {

            JSONObject primary_contact = new JSONObject(s);
            String s1 = primary_contact.getString("cities");
            JSONObject primary_contact1 = new JSONObject(s1);
            String s2 = primary_contact1.getString("city");


            List<City> citiesList = new ObjectMapper().readValue(s2, new TypeReference<List<City>>() { });

            for(City city : citiesList) {
                System.out.println("----------START---------");
                System.out.println(city.getName());
                System.out.println(city.getPopulation());
                System.out.println(city.getTelephonecode());
                System.out.println("---------END----------");
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        WebClient xmlAddClient = WebClient.create(REST_URI);
        xmlAddClient.path(CITIES_BHUVAN).accept("application/json");
        s = xmlAddClient.get(String.class);
        System.out.println(s);

        WebClient plainSubClient = WebClient.create(REST_URI);
        plainSubClient.path(BHUVAN).accept("application/json");
        s = plainSubClient.get(String.class);
        System.out.println(s);

        WebClient xmlSubClient = WebClient.create(REST_URI);
        xmlSubClient.path(BHUVAN_BHUVAN).accept("application/json");
        s = xmlSubClient.get(String.class);
        System.out.println(s);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM