colleagues! I have two objects:
1.
{
"name": "test_name",
"contact": [
{
"street": "st.1",
"phoneNumber": "test_n"
}
]
}
OR
{
"name": "test_name",
"contact": [
{
"street": "st.1",
"phoneNumber": "test_n"
}
],
"additionalInfo": null
}
2.
{
"name": "test_name_2",
"additionalInfo": {
"lastName": "ln",
"age": 24
}
}
I use JsonObject (jackson from java) and I want to set to the first object these fields that it has null, and the second does not. For example, I want to get the first object like:
{
"name": "test_name",
"contact": [
{
"street": "st.1",
"phoneNumber": "test_n"
}
],
"additionalInfo": {
"lastName": "ln",
"age": 24
}
}
Because from the first object this field is null. Is it possible to do something? Thank u!
CodePudding user response:
As far as I know, there is no out of box solution for that.
Based on answer given here, I modified merge()
function to meet your needs.
Here is implementation:
public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) {
Iterator<String> fieldNames = updateNode.fieldNames();
while (fieldNames.hasNext()) {
String fieldName = fieldNames.next();
JsonNode jsonNode = mainNode.get(fieldName);
// if field exists and is an embedded object
if (jsonNode != null && jsonNode.isObject()) {
merge(jsonNode, updateNode.get(fieldName));
} else {
if (mainNode instanceof ObjectNode) {
JsonNode updateNodeValue = updateNode.get(fieldName);
JsonNode mainNodeValue = mainNode.get(fieldName);
if ((Objects.isNull(mainNodeValue) || mainNodeValue.isNull()) && (Objects.nonNull(updateNodeValue) && !updateNodeValue.isNull())) {
((ObjectNode) mainNode).put(fieldName, updateNodeValue);
}
}
}
}
return mainNode;
}
This function will basically take only those properties that exist in the object being passed as the second argument and add those properties to the object being passed as the first argument.
As far as I understand, that's what you need.
If you run code below:
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
final String jsonStringOne = "{\n"
" \"name\": \"test_name\",\n"
" \"contact\": [\n"
" {\n"
" \"street\": \"st.1\",\n"
" \"phoneNumber\": \"test_n\"\n"
" }\n"
" ]\n"
"}";
final String jsonStringTwo = "{\n"
" \"name\": \"test_name_2\",\n"
" \"additionalInfo\": {\n"
" \"lastName\": \"ln\",\n"
" \"age\": 24\n"
" }\n"
"}";
final JsonNode to= mapper.readTree(jsonStringOne);
final JsonNode from = mapper.readTree(jsonStringTwo);
final JsonNode jsonNode = merge(to, from);
System.out.println(jsonNode);
}
You shoud see output like this:
{
"name":"test_name",
"contact": [{"street":"st.1","phoneNumber":"test_n"}],
"additionalInfo":{"lastName":"ln","age":24}
}