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"}]
user3763375
  • 45
  • 1
  • 2
  • 7

1 Answers1

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);
Joey
  • 670
  • 8
  • 14
  • yes. If the object was single item. But it is list and with String items. – user3763375 Oct 08 '19 at 18:59
  • @user3763375 I forgot about type erasure for generics, I've updated my response – Joey Oct 08 '19 at 19:04
  • @user3763375 You can actually also use the basic array type as well, I added the example using `TransEvent[].class` just now – Joey Oct 08 '19 at 19:09
  • 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)); – user3763375 Oct 08 '19 at 19:16
  • I think the problem is input list contains string with double quotes. – user3763375 Oct 08 '19 at 19:16