JSON Tree Model

JSON Tree Model Reader

package com.json.demo7_4_2;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TreeModelReader {
	public static void main(String[] args) throws JsonProcessingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		ClassLoader classLoader = TreeModelReader .class.getClassLoader();
		JsonNode root = objectMapper.readTree(new File(classLoader.getResource("mapJson.json").getFile()));
		JsonNode key1 = root.get("key1");
		System.out.println("Key 1 : "+key1.asText());
		JsonNode array = root.get("Array");
		for(JsonNode x : array) {
			System.out.println(x.asText());
		}
	}
}

JSON Tree Model Writer

package com.json.demo8_4_3;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class TreeModelWrite {
	public static void main(String[] args) throws JsonProcessingException, IOException {
		ObjectMapper objectMapper = new ObjectMapper();
		ClassLoader classLoader = TreeModelWrite .class.getClassLoader();	
		JsonNode root = objectMapper.readTree(new File(classLoader.getResource("mapJson2.json").getFile()));
		System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
		//Removing key2
		((ObjectNode)root).remove("key2");
		System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
	}
}

Leave a Comment