简体   繁体   中英

Object Mapper deserializing map array

   {
       "name" : "test",
       "info": [
          {
            "key1": "test",
            "key2": "blaa",
            "key3": "yadayada"
          },
          {
            "key4": "test1",
            "key5": "blaa1",
            "key6": "yadayada1"
          }
        ],
    }

I have this class for the deserialization

public class Account{
    private String name;
    private Map<String,String>[] info;
}

for some reason info is not getting deserialized... not even with List<Map<String,String>> its always null, and name is working

(im using ObjectMapper )

the code

   ObjectMapper objectMapper = new ObjectMapper();
   objectMapper.disable( DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
   results = objectMapper.readValue(responseBody.getEntity().getContent(), Account.class);

Thanks

The problem lies on the fact that the JSON schema you posted has a wrong comma in the end ) . Try the following

Let's say that the responseBody.getEntity().getContent() is the JSON you posted

Account.java

or more specific

private String name;
private Map<String,String>[] info;
//getters && setters && default constructor

Deserialization method

    Account account = null;
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        account = objectMapper.readValue(responseBody.getEntity().getContent(), Account.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

This is a mixed bag of things wrong.

  1. Your JSON is invalid - ditch the last comma after the closing square bracket
  2. Your POJO shows no accessible methods to set the values (ie deserialize into an Account )
  3. According to your post, the name field is de-serialized, which I imagine implies some accessible setter is actually there but you may not have posted it?
  4. If the info silently fails to serialize, it's likely because your ObjectMapper has been configured with DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES as false - see docs .
  5. You can either have a List<Map<String, String>> for info , or keep the Map<String, String>[] - it's not relevant to your issue.

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