I have an expected json file as below. It is a nested object
{
"contact_info": [{
"contact_id": "Contact_001",
"contact_status": {
"exam_status": 0,
"term_list": [{
"term_code": 110,
"t_list": [{
"s_code": "12001",
"sexam_status": 0
},
{
"s_code": "13001",
"sexam_status": 1
}
]
}]
}
}]
}
How to add all field name and value of all items inside this object into List?
I tried using the following way but it is not as expected.
//Get all key name in json object
```public static List<String> getAllKeysInJsonUsingJsonNodeFieldNames(String json) {
ObjectMapper mapper = new ObjectMapper()
List<String> keys = new ArrayList<>();
JsonNode jsonNode = mapper.readTree(json);
getAllKeysUsingJsonNodeFields(jsonNode, keys);
return keys;
}
public static void getAllKeysUsingJsonNodeFields(JsonNode jsonNode, List<String> keys) {
if (jsonNode.isObject()) {
Iterator<Map.Entry<String, JsonNode>> fields = jsonNode.fields();
fields.forEachRemaining({def field ->
keys.add(field.getKey());
getAllKeysUsingJsonNodeFields((JsonNode) field.getValue(), keys);
});
} else if (jsonNode.isArray()) {
ArrayNode arrayField = (ArrayNode) jsonNode;
arrayField.forEach({def node ->
getAllKeysUsingJsonNodeFields(node, keys);
});
}
}```
The result as below => It only shows only field name without figure out that field belong to which object
TagName[i] = s_code
I expect that the result should be below, specifically, I want to field name should be shown it belongs to which object => Could you tell me how to resolve it?
TagName[i] = contact_status.term_list[0].t_list[0].s_code
Sorry for I’m a new in Java => If anyone know a way to resolve it please tell me in more details. Thank you so much!
3
Answers
Below code for add field names and values of a JSON object into List<String> using jsonNode:
This code does what you want.
The return String is:
And this String is the same Json as yours. Basically you need to build your map the way you want your JSON to look and than just serialize it to Json. In This code I used classes
JsonUtils
andTextUtils
.JsonUtils
class is a thin wrapper over Jason-Jackson library and it makes serializing and parsing simpler. Thise classes come from Open Source MgntUtils library written and maintained by me. You can get this library as Maven artifact here or here and also on Github with source code and Javadoc. Here isJsoonUtils
JavadocYou can use JSON library such as Josson to do the transformation.
https://github.com/octomix/josson
Deserialization
Query the keys and values in separate arrays
Output
Query the keys and values in single array
Output