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

后端 未结 2 415
情歌与酒
情歌与酒 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: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 map = mapper.readValue(JSON_STRING, new TypeReference>(){});
    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!

提交回复
热议问题