0

Not the duplicate of How to use Jackson to deserialise an array of objects.

Here in the list ,items are string within double quotes.

I am trying to convert a list of messages which are jsonString to List of UserDefined objects. I have input like this.

[
    "{\"id\":\"5\",\"type\":\"abc\",\"innerObject\":{\"id\":\"8\"}}"
]

What is the method to convert this list to List of MyClass.

class MyClass{
String id;
String type;
Inner inner;
//getters and setters
}
class Inner{
String id;
//getters and setters
}

I have tried

objectMapper.readValue(jsonFormattedString, new TypeReference<List<MyClass>>(){});

Also this

Type listType = new TypeToken<ArrayList<MyClass>>() {}.getType();
myList = new Gson().fromJson(jsonFormattedString, listType);

But not working.

Expected output is

[{"id":"5","type":"abc","innerObject":"8"}]
6
  • Have you tried Gson? Commented Oct 8, 2019 at 18:51
  • yes. I have tried this. updated query . Commented Oct 8, 2019 at 18:53
  • can you update the complete class with getters and setters Commented Oct 8, 2019 at 18:57
  • You have innerObject inside the jsonString, but the property in the MyClass is called inner and not innerObject. Can it be that the problem why it's not working? Commented Oct 8, 2019 at 19:13
  • But the error is even before that as the input list contains String with double quotes. Commented Oct 8, 2019 at 19:18

1 Answer 1

0

For the readValue method of ObjectMapper, the second argument should be the class and not a class instance. For example, if this were a single item you would call readValue as shown below:

objectMapper.readValue(jsonFormattedString, TransEvent.class);

For a generic list, this can be accomplished either of the following ways:

// list
objectMapper.readValue(jsonFormattedString, new TypeReference<List<TransEvent>>(){});

// list
objectMapper.readValue(jsonFormattedString, objectMapper.getTypeFactory().constructCollectionType(List.class, TransEvent.class));

// array
TransEvent[] transEvents = objectMapper.readValue(jsonFormattedString, TransEvent[].class);
Sign up to request clarification or add additional context in comments.

5 Comments

yes. If the object was single item. But it is list and with String items.
@user3763375 I forgot about type erasure for generics, I've updated my response
@user3763375 You can actually also use the basic array type as well, I added the example using TransEvent[].class just now
com.fasterxml.jackson.core.JsonParseException: Unexpected close marker ']': expected '}' (for root starting at [Source: ] when I tried objectMapper.readValue(jsonFormattedString, objectMapper.getTypeFactory().constructCollectionType(List.class, TransEvent.class));
I think the problem is input list contains string with double quotes.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.