0

I have such a JSON formatted string and the key is a random number.

{
  "tasks": {
    "0": {
     "key1": "value1"
    },
    "100": {
      "key1": "value2"
    }
}

How can I convert it to Java object by using Jackson?

How to define the Java class so that I can use Jackson like this?

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(myStr, XXXX);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Dragon
  • 487
  • 4
  • 17

1 Answers1

2

There are a couple of approaches you could use depending on your needs:

Using JsonNode

You could parse your JSON into the Jackson tree model. That is, into JsonNode from the com.fasterxml.jackson.databind package:

ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);

You also can use Jackson to parse a JsonNode into a POJO:

MyBean bean = mapper.treeToValue(jsonNode, MyBean.class);

Using Map<String, Object>

Depending on your requirements, you could use a Map<String, Object> instead of JsonNode:

ObjectMapper mapper = new ObjectMapper();
Map<String, Object> parsed = mapper.readValue(json, 
                                 new TypeReference<Map<String, Object>>() {});

To convert a map into a POJO, use:

MyBean bean = mapper.convertValue(map, MyBean.class);
cassiomolin
  • 124,154
  • 35
  • 280
  • 359