Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize JSON to a Map<String, Object> member variable using Jackson?

Tags:

java

json

jackson

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

  {
      "created_date": "2015-11-11",
      "generation_date": "2015-11-12T20:35:00+0000",
      "values": {
          "MORNING": 13,
          "EVENING": 18,
          "NOON": 446,
          "NIGHT": "0.60.0"
      },
      "id": "12345"
  }

And my Box object looks like:

public class Box {
    @JsonProperty
    Map<String, Object> json;

    public Box() {
        // Blank
    }

    // Getter and setter for `json` field
}

This is the code I have:

Box box = null;
// `JSON_STRING` below refers to a string of the above JSON
metricsPacket = new ObjectMapper().readValue(JSON_STRING, Box.class);

I keep getting this error:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "created_date" (class com.me.Box), not marked as ignorable (one known property: "json"])

All of the examples I've found online are just deserializing JSON to a simple POJO with a handful of String or int member variables. How can I properly map my JSON to my json field and have it behave correctly?

I'd imagine that once this works json.get("id") would return 12345 while json.get("values") would return another Map<String, Object> (or Map<String, String>). I'm still new to using Jackson, so this also might not even be the right way to do what I want to do. Any help would be appreciated!

like image 825
yiwei Avatar asked Nov 13 '15 00:11

yiwei


People also ask

How does Jackson deserialize dates from JSON?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);


1 Answers

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!

like image 108
Lucas Crawford Avatar answered Sep 17 '22 18:09

Lucas Crawford