Issue
JSON representation fruit: { "type": "sweet", "value": "Apple" } I want to perform concise representations like this.
fruit: "Apple"
Solution
You need to parse the string to JsonNode and then iterate over nodes and replace its value also check not a null child to avoid replacing a single node with a null value.
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ \"id\": \"123\", \"type\": \"fruit\", \"veritey1\": { \"type\": \"Property\", \"value\": \"moresweetappler\" }, \"quantity\": { \"type\": \"Property\", \"value\":10 } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
if (node.getValue().hasNonNull("value")) {
((ObjectNode) nodes).set(node.getKey(), node.getValue().get("value"));
}
}
System.out.println(nodes.toString());
}
Output:
{"id":"123","type":"fruit","veritey1":"moresweetappler","quantity":10}
public static void main(String[] args) throws JsonMappingException, JsonProcessingException {
String data =
"{ \"tank\": { \"type\": \"Relationship\", \"object\": \"id007\", \"time\": \"2017-07-29T12:00:04Z\", \"providedBy\": { \"type\": \"Relationship\", \"object\": \"id009\" } } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodes = mapper.readTree(data);
Iterator<Entry<String, JsonNode>> iterator = nodes.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> node = iterator.next();
reduceJson(node.getValue());
}
System.out.println(nodes.toString());
}
public static void reduceJson(JsonNode node) {
if (node.hasNonNull("type")) {
((ObjectNode) node).remove("type");
}
Iterator<Entry<String, JsonNode>> iterator = node.fields();
while (iterator.hasNext()) {
Entry<String, JsonNode> childnode = iterator.next();
if (childnode.getValue().isObject()) {
reduceJson(node.get(childnode.getKey()));
}
}
}
Output:
{"tank":{"object":"id007","time":"2017-07-29T12:00:04Z","providedBy":{"object":"id009"}}}
Answered By - Dhaval Gajjar
Answer Checked By - Mildred Charles (JavaFixing Admin)