Compare with name and update that json element.
Resource resource = new ClassPathResource("gateway-fields.json"); //read from json file
JsonFactory jsonFactory = new JsonFactory();
ObjectMapper objectMapper = new ObjectMapper(jsonFactory);
JsonNode arrayNode = objectMapper.readTree(resource.getFile()).get("fields");
if (arrayNode.isArray()) {
for (JsonNode jsonNode : arrayNode) {
String nameFieldNode = jsonNode.get("name").asText();
if("RefNo".equals(nameFieldNode)){
((ObjectNode)jsonNode).put("name", "1112");
}
}
}
Answer from Kaustubh Khare on Stack OverflowThis will work for you :
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
Map<String, String> map = new HashMap<>();
addKeys("", root, map, new ArrayList<>());
map.entrySet()
.forEach(System.out::println);
private void addKeys(String currentPath, JsonNode jsonNode, Map<String, String> map, List<Integer> suffix) {
if (jsonNode.isObject()) {
ObjectNode objectNode = (ObjectNode) jsonNode;
Iterator<Map.Entry<String, JsonNode>> iter = objectNode.fields();
String pathPrefix = currentPath.isEmpty() ? "" : currentPath + "-";
while (iter.hasNext()) {
Map.Entry<String, JsonNode> entry = iter.next();
addKeys(pathPrefix + entry.getKey(), entry.getValue(), map, suffix);
}
} else if (jsonNode.isArray()) {
ArrayNode arrayNode = (ArrayNode) jsonNode;
for (int i = 0; i < arrayNode.size(); i++) {
suffix.add(i + 1);
addKeys(currentPath, arrayNode.get(i), map, suffix);
if (i + 1 <arrayNode.size()){
suffix.remove(arrayNode.size() - 1);
}
}
} else if (jsonNode.isValueNode()) {
if (currentPath.contains("-")) {
for (int i = 0; i < suffix.size(); i++) {
currentPath += "-" + suffix.get(i);
}
suffix = new ArrayList<>();
}
ValueNode valueNode = (ValueNode) jsonNode;
map.put(currentPath, valueNode.asText());
}
}
For the json you gave the output will be :
name-items-name-1-2=2nditem
name-items-name-1-1=firstitem
name-items-stock-1-1=12
name-first-1=John
name-items-stock-1-2=23
company=John Company
name-last-1=Doe
elements() gives you an iterator for subnodes and fields() gives you the properties.
With that, you can code a recursive function that walks through all nodes.
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())
As you found in your comment, JsonNode has a .AsArray() method which internally uses pattern matching to return a JsonArray. This isn't super safe, however, since it will throw an exception if productSizes isn't deserialized as a JsonArray.
For better safety, you are probably better off either using a try-catch or implementing the pattern matching yourself, like in the following:
if (productSizes is JsonArray jArray)
{
foreach (var size in jArray)
{
Console.WriteLine(size);
Console.WriteLine();
}
} else {
Console.WriteLine("Error: productSizes is not an array!");
}
Check if productSizes is a JsonArray and iterate it:
if (productSizes is JsonArray jArr)
{
foreach (var node in jArr)
{
// ...
}
}
Read more:
- Type-testing operators and cast expressions
- JSON DOM choices