Jimmy Zoto
Jimmy Zoto

Reputation: 1763

Jackson : partial deserialization to List<String>

I have a use case where I need to use Jackson to deserialize JSON like :

[
    {"prop1":"value1","prop2":"value2"},
    {"prop1":"value3","prop2":"value4"},
    ...
|

to a List<String> where the elements of the List are the JSON strings like

"{\"prop1\":\"value1\",\"prop2\":\"value2\"}"

It seems like @JsonRawValue might be useful here, but I'm not sure how to use it (and would prefer not to create a model class with a single string to hold the value).

Upvotes: 0

Views: 1462

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280174

With Java 8, you can get a List of ObjectNode elements and map and collect it to a List of String elements.

List<ObjectNode> list = mapper.readValue(json, new TypeReference<List<ObjectNode>>() {});
List<String> strings = list.stream().map(node -> node.toString()).collect(Collectors.toList());

Without Java 8, you can do the same thing, but manually.

Upvotes: 2

Related Questions