简体   繁体   中英

Unable to map json string to java object using jackson API

I am writing a web service (server + client). I am able to make a service and it returns me the following json

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

}

my POJO's are

@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;
}
}

Now I want to write a client which will map this json to my POJO so that I get a RestFulCities Object populated in java

My client code is below:

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();
    }
}
 }

But the issue is: I am getting the following exception

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"])

When I am using below property:

@JsonIgnoreProperties(ignoreUnknown = true)

Although I donot get the exception, but my restFulCityList is null which is not desired

Please help

You are using JAXB annotations so you need to properly configure your ObjectMapper with the correct module; you need the jackson-module-jaxb-annotations project. Add it using your favorite dependency management system and use it like this:

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

Note: this is for Jackson 2.x. Jackson 1.x support JAXB by default, but that version is not supported anymore and given that you are having this problem you are probably using Jackson 2.x anyways.

Update: JAXB annotation are great for interop with XML system, but you should really use Jackson's own annotation if you can. That would remove the need for the jaxb module and the configuration of the ObjectMapper . Also, there are some functionality in Jackson only available through its annotation because there is no equivalent in JAXB.

Found the solution..

use the following code :

 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>>() { });

Client code should be :

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM