1

Lets say that you have a json array that looks as follows :

[
  {
    "id" : 1,
    "first_name" : "Jane",
    "last_name" : "Doe"
  },
  {
    "id" : 2,
    "first_name" : "John",
    "middle_name" : "Q",
    "last_name" : "Public",
    "birth_year" : 1971
  },
  {
    "id" : 3,
    "anonymous_user" : true,
    "crm_id" : "abc123"
   },
   {
    "id" : 4,
    "first_name" : "Albert",
    "last_name" : "Einstein",
    "profession" : "Scientist",
    "birth_year" : 1879,
    "e_equals_mc_squared" : true
  }
]

The goal is to use Jackson to marshal to POJO. My thinking is that I could have a class to contain each K,V pair .. something like :

public class myDataObject {
    private String key;
    private T value;

    ...
}

And maybe a container class for that :

public class myDataContainer {
   private ArrayList<myDataObject> dataList;

   ...
}

My question becomes what does marshaling that look like using jackson? There is no schema for the json, each json object can have an unspecified number of K,V pairs and the list of keys is also unspecified.

Does something like this work? Is this even the right approach?

ArrayList<myDataContainer> dataList = mapper.readValue(jsonFile, new TypeReference<ArrayList<myDataContainer>() {}); 

1 Answer 1

2

What your JSON really is, is a list of maps - with Strings as keys and Objects as values.

So, using Jackson, you should be able to do:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.