How can I deserialize JSON to a Map member variable using Jackson?

后端 未结 2 399
情歌与酒
情歌与酒 2021-01-17 16:55

I have some JSON I would like to map to my Boxobject:

  {
      \"created_date\": \"2015-11-11\",
      \"generation_date\": \"2015-11-12T20:35:         


        
相关标签:
2条回答
  • 2021-01-17 17:26

    I think you need to add an annotated argument to your constructor. For example,

    public Box(@JsonProperty("json") Map<String, Object> json) {
        // TODO
    }
    
    0 讨论(0)
  • 2021-01-17 17:37

    First, addressing your problem. You are trying to de-serialize JSON to a class that doesn't have fields present in the JSON string, so it's failing to find those fields and returning the exception.

    You could alternatively do the following:

    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(JSON_STRING, new TypeReference<Map<String, String>>(){});
    box.setJsonMap(map);
    

    where box would have a setter to set the json map

    Or you could add all the fields to your Box POJO and use GSON to make this easier!

    E.g. Json -> Object

    Gson gson = new Gson();
    Box box = gson.fromJson(JSON_STRING, Box.class);
    

    E.g. Object -> Json

    Gson gson = new Gson();
    String str = gson.toJson(mBox); //mBox is some box object
    

    GSON would populate all the fields within box to match the key, value pairs found in the JSON string. Ignore this if you don't want to do that but it is another alternative!

    0 讨论(0)
提交回复
热议问题