1

I have JSON data like that:

[ {
    "data": "data",
    "what": "what2",
    "when": 1392046352,
    "id": 13,
    "tags": "checkid:testcheckid, target:server.id.test, id:testid"
}, {
    "data": "Test",
    "what": "Test",
    "when": 1395350977,
    "id": 5,
    "tags": "checkid:testcheckid, target:server.id.test, id:testid"
} ]

I have a Java class and I want to convert this JSON to a list of instances of my class. I found how to convert a single object, but not a list.

3 Answers 3

1

With Jackson you would do something like:

String jsonStr = "...";
ObjectReader reader = new ObjectMapper().reader();
List<Map<String, Object>> objs = reader.readValue(jsonStr);

Map<String, Object> myFirstObj = objs.get(0);
myFirstObj.get("data");
myFirstObj.get("what");
// and so on

Or even better you can create a pojo and do:

String jsonStr = "...";
ObjectMapper mapper = new ObjectMapper();
List<MyPojo> myObjs = mapper.readValue(jsonStr, new TypeReference<List<MyPojo>>() {});
MyPojo myPojo = myObjs.get(0);
myPojo.getData();
myPojo.getWhat();
// and so on
Sign up to request clarification or add additional context in comments.

5 Comments

Might as well use JsonNode if values can be anything
As in Map<String, JsonNode>?
No, as in JsonNode ;) It can model any JSON value
In hedi691's case we would want ArrayNode? I've used jackson but havn't used the 'Node' objs. Is there a benefit to doing so?
If he has the POJO, no. If it is to manipulate JSON directly, yes. The .get() methods are defined on JsonNode after all (note also the .path() methods)
0

There are several libraries out there that will parse JSON, such as GSon and Jackson. If the functionality isn't provided out-of-box, you can write a custom deserializer that will do what you need.

Comments

0

I don't really understand your problem, if you already have and object just create a list (ArrayList for example) and add them.

ArrayList<YourObject> list = new ArrayList<YourObject>();
list.add(yourObject);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.