Acquire an ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode).
For example, to get a List<String> out of a JSON array containing only JSON strings
CopyObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
});
// use it
List<String> list = reader.readValue(arrayNode);
Answer from Sotirios Delimanolis on Stack OverflowAcquire an ObjectReader with ObjectMapper#readerFor(TypeReference) using a TypeReference describing the typed collection you want. Then use ObjectReader#readValue(JsonNode) to parse the JsonNode (presumably an ArrayNode).
For example, to get a List<String> out of a JSON array containing only JSON strings
CopyObjectMapper mapper = new ObjectMapper();
// example JsonNode
JsonNode arrayNode = mapper.createArrayNode().add("one").add("two");
// acquire reader for the right type
ObjectReader reader = mapper.readerFor(new TypeReference<List<String>>() {
});
// use it
List<String> list = reader.readValue(arrayNode);
If an Iterator is more useful...
...you can also use the elements() method of ArrayNode. Example see below.
sample.json
Copy{
"first": [
"Some string ...",
"Some string ..."
],
"second": [
"Some string ..."
]
}
So, the List<String> is inside one of the JsonNodes.
Java
When you convert that inner node to an ArrayNode you can use the elements() method, which returns an Iterator of JsonNodes.
CopyFile file = new File("src/test/resources/sample.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(file);
ArrayNode arrayNode = (ArrayNode) jsonNode.get("first");
Iterator<JsonNode> itr = arrayNode.elements();
// and to get the string from one of the elements, use for example...
itr.next().asText();
New to Jackson Object Mapper?
I like this tutorial: https://www.baeldung.com/jackson-object-mapper-tutorial
Update:
You can also use .iterator() method of ArrayNode. It is the same:
Same as calling
.elements(); implemented so that convenience "for-each" loop can be used for looping over elements of JSON Array constructs.
from the javadocs of com.fasterxml.jackson.core:jackson-databind:2.11.0
Yes, the Jackson manual parser design is quite different from other libraries. In particular, you will notice that JsonNode has most of the functions that you would typically associate with array nodes from other APIs. As such, you do not need to cast to an ArrayNode to use. Here's an example:
JSON:
{
"objects" : ["One", "Two", "Three"]
}
Code:
final String json = "{\"objects\" : [\"One\", \"Two\", \"Three\"]}";
final JsonNode arrNode = new ObjectMapper().readTree(json).get("objects");
if (arrNode.isArray()) {
for (final JsonNode objNode : arrNode) {
System.out.println(objNode);
}
}
Output:
"One"
"Two"
"Three"
Note the use of isArray to verify that the node is actually an array before iterating. The check is not necessary if you are absolutely confident in your data structure, but it's available should you need it (and this is no different from most other JSON libraries).
In Java 8 you can do it like this:
import java.util.*;
import java.util.stream.*;
List<JsonNode> datasets = StreamSupport
.stream(obj.get("datasets").spliterator(), false)
.collect(Collectors.toList())
You need to get the ArrayList from JsonNode. Here is your solution.
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(json);
String sender = jsonNode.get(0).get("sender").textValue();
JsonNode contains multiple objects. Due to read all sender elements, you may use following code.
public static void main(String[] args) throws IOException {
File file = new File("src\\main\\java\\json.txt");
FileInputStream value = new FileInputStream(file);
ObjectMapper object = new ObjectMapper();
JsonNode jsonNode = object.readTree(value);
for (int i=0;i<jsonNode.size();i++){
System.out.println(jsonNode.get(i).findValue("sender").textValue());
}
}
ObjectMapper mapper = new ObjectMapper();
List<Employee> e = new ArrayList<Employee>();
ArrayNode array = mapper.valueToTree(e);
ObjectNode companyNode = mapper.valueToTree(company);
companyNode.putArray("Employee").addAll(array);
JsonNode result = mapper.createObjectNode().set("company", companyNode);
List<String> yourList = new ArrayList<>();
((ObjectNode) someNode).set("listname", this.objectMapper.valueToTree(yourList));
Moving my comment to an answer, as it got upvoted a lot.
This should do what the OP needed:
new ObjectMapper().convertValue(jsonNode, ArrayList.class)
A quick way to do this using the tree-model... convert the JSON string into a tree of JsonNode's:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree("...<JSON string>...");
Then extract the child nodes and convert them into lists:
List<Double> x = mapper.convertValue(rootNode.get("x"), ArrayList.class);
List<Double> y = mapper.convertValue(rootNode.get("y"), ArrayList.class);
A slight longer, but arguable better way to do this is to define a class representing the JSON structure you expect:
public class Request {
List<Double> x;
List<Double> y;
}
Then deserialized directly as follows:
Request request = mapper.readValue("...<JSON string>...", Request.class);
Thanks for all the replies :)
I required the JsonNode coming via REST request containing key->value pairs to be converted into an ArrayList<OptionalHeader>, see the OptionalHeader class in question.
finally did it using following:
(getting it as JsonNode in my POJO) coming via REST request. I used below in my setter.
public void setOptHeaders(JsonNode optHeaders) throws JsonParseException, JsonMappingException, IOException {
this.optHeaders = optHeaders;
List<OptionalHeader> allHeaders = new ArrayList<OptionalHeader>();
Iterator<Entry<String, JsonNode>> nodeIterator = optHeaders.fields();
while (nodeIterator.hasNext()) {
Map.Entry<String, JsonNode> entry = (Map.Entry<String, JsonNode>) nodeIterator.next();
OptionalHeader header = new OptionalHeader(entry.getKey(),entry.getValue().asText());
allHeaders.add(header);
}
optionalEmailHeaders.addAll(allHeaders);
}
then following in the getter to convert it back.
public JsonNode getOptHeaders() {
final ObjectMapper mapper = new ObjectMapper();
final Map<String, String> map = new HashMap<String, String>();
for (final OptionalHeader data: optionalEmailHeaders)
map.put(data.getName(), data.getValue());
optHeaders = mapper.valueToTree(map);
return optHeaders;
}
Jackson mapper is there which can map Java Objects from/to JSON objects.
You can get the Jackson API from here.
Try saving your JSON string into a file eg. 'headers.json'.
Jackson provides a ObjectMapper class and you can use its readValue( File file, Class class) method to get the Java object from JSON like :-
ObjectMapper mapper = new ObjectMapper();
OptionalHeader optHeader= mapper.readValue(new File("c:\\headers.json"), OptionalHeader .class);
You can use the same link for getting the docs & read more about it.