user2478236
user2478236

Reputation: 687

Mapping Json to Java POJO Using Jackson

{  
   "query":{  
      "data":{  
         "val1":{  
            "id":123,  
            "name":"abc"  
         },  
         "val2":{  
            "id":13,  
            "name":"def"  
         },  
         "total":{  
            "count":2,  
            "page":{  
               "num":1  
            }  
         }  
      }  
   }  
}  

My json looks like above. "val1",val2" are dynamic , so i am mapping it to a Map.Everything worked fine till i got "total" tag. Since the structure is different the mapping to object is failing. How can i skip "total" tag while parsing or parse "total" to a different object.

I get below exception

Exception in thread "main" java.lang.IllegalArgumentException: Instantiation of [simple type, class jsom.schema.pojo.Definitions] value failed: Unrecognized field "count" (Class jsom.schema.pojo.MainResourceObj), not marked as ignorable
 at [Source: java.io.StringReader@5933cca2; line: 4, column: 26] (through reference chain: jsom.schema.pojo.Definitions["definitions"]->jsom.schema.pojo.MainResourceObj["count"])

I updated my pojo like below , still the total tag is getting into Map.which causes exception

HashMap<String, customObject> definitions;  
@JsonProperty("total")  
Total total;  

public class Total {

    public Total() {
        // TODO Auto-generated constructor stub
    }
    String count;
    Page page;
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    public Page getPage() {
        return page;
    }
    public void setPage(Page page) {
        this.page = page;
    }

    @JsonCreator
    public static Total Create(String jsonString) throws JsonParseException,
            JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        Total module = null;
        module = mapper.readValue(jsonString, Total.class);
        return module;
    }

}

Upvotes: 1

Views: 745

Answers (2)

David
David

Reputation: 3055

If you want to ignore a property (aka field) you should use either @JsonIgnore or @JsonIgnoreProperties annotations.

Your code would then either become:

HashMap<String, customObject> definitions;
@JsonProperty("total")  
Total total;  

or

...
@JsonIgnoreProperties({"total"})
... class ... {
HashMap<String, customObject> definitions;
Total total;  
...

Using JsonIgnoreProperties allows you to exclude more than one property in a single place.

Upvotes: 1

Colleen Stock
Colleen Stock

Reputation: 51

I think you want to use a @JsonIgnore tag here above your variable declaration. Try that out!

@JsonIgnore  
Total total; 

Upvotes: 1

Related Questions