rwinner
rwinner

Reputation: 418

JSON parse with Objectmapper JAVA

This is the JSON string:

{
   "d":{
      "results":[
         {
            "__metadata":{
               "uri":"http://blabla1",
               "type":"type1"
            },
            "Synonym":"miami"
         },
         {
            "__metadata":{
               "uri":"http://blabla2",
               "type":"type2"
            },
            "Synonym":"florida"
         }
      ]
   }
}

This is the code:

public class Test{        
    @JsonIgnoreProperties(ignoreUnknown = true)
    public static class d {
        public List<Results> results;
        public d() {
            results = new ArrayList<Results>();
        }
        public static class Results {
            public Metadata __metadata;
            public String Synonym;
            public Results() {}
        }
        public static class Metadata {
            public String uri;
            public String type;
            public Metadata() {}
        }
    }
}

With the following mapper:

ObjectMapper mapper = new ObjectMapper();
Test.d readValue = mapper.readValue(jsonString, Test.d.class);
for (Test.d.Results k : readValue.results) {
    System.out.println("synonym: "+k.Synonym);
}

It gives me no error, just an empty arraylist of results... p.s. i have made a lot of changes in between time, sorry for the inconvenience

Upvotes: 1

Views: 5892

Answers (2)

rwinner
rwinner

Reputation: 418

I have managed to solve it. i forgot to make setters and getters for class 'd'.

public class Test {
    private d d;
    public d getD() {return d;}
    public void setD(d d) {this.d = d;}    
    public static class d{
        private List<Results> results;
        public List<Results> getResults() {return results;}
        public void setResults(List<Results> results) {this.results = results;}
    }
    public static class Results {
        public Metadata __metadata;
        public String Synonym;
    }
    public static class Metadata {
        private String uri;
        private String type;
        public String getUri() {return uri;}
        public void setUri(String uri) {this.uri = uri;}
        public String getType() {return type;}
        public void setType(String type) {this.type = type;}
    }
}

This is the map:

Test test = mapper.readValue(json, KeyPhrase.class);
    System.out.println("cp");

    for(Test.Results res : test.getD().getResults()){
        System.out.println(res.Synonym);
}

Upvotes: 1

Rafa Romero
Rafa Romero

Reputation: 2716

you must create an object that fits with the jSon answer, something like this (not tested):

class d {

    public List<Results> results;

    public d() {
    }
}

class Results {

    public Metadata metadata;
    public String synonym;

    public Results() {
    }
}

class Metadata {

    public String uri;
    public String type;


    public Metadata() {
    }
}

Hope it helps!

Upvotes: 2

Related Questions