본문 바로가기
개발 공부 기록하기/- Kotlin & Java

[Java-lib] Object Mapper에 대해서

by soulduse 2016. 3. 8.
반응형

Object Mapper 라이브러리 사용관련 자료 조사


며칠전 아는형님의 소개로 Object Mapper에 대해 알게 되었다.

그동안 JSON값 활용을 위해 직접 파싱을 하고 인터페이스를 만드는등 번거로운 노가다(?) 작업이 필요했는데,
사용해보니 직접 파싱 or GSON 보다 훨씬 ObjectMapper이 깔끔하고 간단하게 데이터를 가공할수 있었다.

앞으로 JSON관련 파싱은 이를 바탕으로 할 것같다.



1. 사용방법에 대해 잘 나와있다.

http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

---------------------------------------------------------------------------------------------------------------------------------------


In this tutorial, we show you how to use Jackson 1.x data binding to convert Java object to / from JSON.

Note
Jackson 1.x is a maintenance project, please use Jackson 2.x instead.
Note
This tutorial is obsolete, no more update, please refer to the latest Jackson 2 tutorial – Object to / from JSON.

1. Quick Reference

1.1 Convert Java object to JSON, writeValue(...)

Java
ObjectMapper mapper = new ObjectMapper();
User user = new User();

//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);

1.2 Convert JSON to Java object, readValue(...)

Java
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object
User user = mapper.readValue(new File("c:\\user.json"), User.class);

//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);

P.S All examples are tested with Jackson 1.9.13

2. Jackson Dependency

For Jackson 1.x, it contains 6 separate jars for different purpose, in most cases, you just need jackson-mapper-asl.

pom.xml
Java
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>

3. POJO (Plain Old Java Object)

An User object for testing.

User.java
Java
package com.mkyong.json;

import java.util.List;

public class User {

	private String name;
	private int age;
	private List<String> messages;

	//getters and setters
}

4. Java Object to JSON

Convert an user object into a JSON formatted string.

JacksonExample.java
Java
package com.mkyong.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {
	public static void main(String[] args) {

		ObjectMapper mapper = new ObjectMapper();

		//For testing
		User user = createDummyUser();
		
		try {
			//Convert object to JSON string and save into file directly 
			mapper.writeValue(new File("D:\\user.json"), user);
			
			//Convert object to JSON string
			String jsonInString = mapper.writeValueAsString(user);
			System.out.println(jsonInString);
			
			//Convert object to JSON string and pretty print
			jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("mkyong");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}

Output

Bash
//new json file is created in D:\\user.json"

{"name":"mkyong","age":33,"messages":["hello jackson 1","hello jackson 2","hello jackson 3"]}

{
  "name" : "mkyong",
  "age" : 33,
  "messages" : [ "hello jackson 1", "hello jackson 2", "hello jackson 3" ]
}

5. JSON to Java Object

Read JSON string and convert it back to a Java object.

JacksonExample.java
Java
package com.mkyong.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonExample {
	public static void main(String[] args) {

		ObjectMapper mapper = new ObjectMapper();

		try {

			// Convert JSON string from file to Object
			User user = mapper.readValue(new File("G:\\user.json"), User.class);
			System.out.println(user);

			// Convert JSON string to Object
			String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
			User user1 = mapper.readValue(jsonInString, User.class);
			System.out.println(user1);

		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Output

Bash
User [name=mkyong, age=33, messages=[hello jackson 1, hello jackson 2, hello jackson 3]]

User [name=mkyong, age=33, messages=[msg 1, msg 2]]

6. @JsonView

@JsonView has been supported in Jackson since version 1.4, it lets you control what fields to display.

6.1 A simple class.

Views.java
Java
package com.mkyong.json;

public class Views {

	public static class NameOnly{};
	public static class AgeAndName extends NameOnly{};

}

6.2 Annotate on the fields you want to display.

User.java
Java
package com.mkyong.json;

import java.util.List;
import org.codehaus.jackson.map.annotate.JsonView;

public class User {

	@JsonView(Views.NameOnly.class)
	private String name;

	@JsonView(Views.AgeAndName.class)
	private int age;
	
	private List<String> messages;

	//getter and setters
}

6.3 Enable the @JsonView via writerWithView().

JacksonExample.java
Java
package com.mkyong.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;

public class JacksonExample {
	public static void main(String[] args) {

		ObjectMapper mapper = new ObjectMapper();
		//By default all fields without explicit view definition are included, disable this
		mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
		 
		//For testing
		User user = createDummyUser();
		
		try {
			//display name only
			String jsonInString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			//display namd ana age
			jsonInString = mapper.writerWithView(Views.AgeAndName.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("mkyong");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}

Output

Bash
{"name":"mkyong"}
{"name":"mkyong","age":33}



2. 한글이라서 좋고 깔끔하게 설명을 잘 해놓으셨다.

 http://noritersand.tistory.com/240

----------------------------------------------------------------------------------------------------------------------------------------


관련 문서


Map - JSON간 변환


writeValueAsString()

writeValueAsString( value ) 

  • value: String 타입으로 변환할 대상


readValue()

readValue( arg, type )

  • arg: 지정된 타입으로 변환할 대상
  • type: 대상을 어떤 타입으로 변환할것인지 클래스를 명시한다. Class객체, TypeReference객체가 올 수 있다.

ex)

mapper.readValue(arg, ArrayList.class);
mapper.readValue(arg, new ArrayList<HashMap<StringString>>().getClass());
mapper.readValue(arg, new TypeReference<ArrayList<HashMap<StringString>>>(){});
cs


map

맵 타입이 JSON 형식의 String 타입으로 변환된다. 자바스크립트에 JSON을 넘겨줄 때 유용하다. 

import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Test2 {
    public static void main(String[] args) throws Exception {
 
        ObjectMapper mapper = new ObjectMapper();
 
        HashMap<StringString> map = new HashMap<StringString>();
        map.put("name""steave");
        map.put("age""32");
        map.put("job""baker");
 
        System.out.println(map);
        System.out.println(mapper.writeValueAsString(map));
    }
}
 
// {age=32, name=steave, job=baker}
// {"age":"32","name":"steave","job":"baker"}
cs

위와 반대로 JSON을 맵 타입으로 변환하려면 다음처럼 작성한다:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Test2 {
    public static void main(String[] args) throws Exception {
 
        ObjectMapper mapper = new ObjectMapper();
        HashMap<StringString> map = new HashMap<StringString>();
 
        String jsn = "{\"age\":\"32\",\"name\":\"steave\",\"job\":\"baker\"}";
        
        map = mapper.readValue(jsn, 
                new TypeReference<HashMap<StringString>>() {});        
        
        System.out.println(map);
    }
}
 
// {name=steave, age=32, job=baker}
cs


List<Map>

다음은 view에 전달할 model이 List<map<?, ?>> 타입일 때 이를 JSON으로 변환하는 방법이다. 사용방법은 크게 다르지 않고 writeValueAsString, readValue 메서드를 사용하되 타입 명시만 달리한다.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
 
public class Test2 {
    public static void main(String[] args) throws Exception {
 
        ObjectMapper mapper = new ObjectMapper();
 
        // map -> json
        ArrayList<HashMap<StringString>> list 
                = new ArrayList<HashMap<String,String>>(); 
        
        HashMap<StringString> map = new HashMap<StringString>();
        map.put("name""steave");
        map.put("age""32");
        map.put("job""baker");
        list.add(map);
        
        map = new HashMap<StringString>();
        map.put("name""matt");
        map.put("age""25");
        map.put("job""soldier");
        list.add(map);
        
        System.out.println(mapper.writeValueAsString(list));
        
        // json -> map
        String jsn = "[{\"age\":\"32\",\"name\":\"steave\",\"job\":\"baker\"},"
                + "{\"age\":\"25\",\"name\":\"matt\",\"job\":\"soldier\"}]";
        list = mapper.readValue(jsn, 
                new TypeReference<ArrayList<HashMap<StringString>>>() {});        
        
        System.out.println(list);
    }
}
 
 
// [{"age":"32","name":"steave","job":"baker"},{"age":"25","name":"matt","job":"soldier"}]
// [{name=steave, age=32, job=baker}, {name=matt, age=25, job=soldier}]
cs




3. 설명이 디테일하여 참고하기 좋았다.

 http://noritersand.tistory.com/240

----------------------------------------------------------------------------------------------------------------------------------------

This page will describe how to read JSON into Java object and write java object into JSON output using Jackson API. Jackson has different API like ObjectMapper, JsonParser and JsonGenerator etc. We can read JSON from different resources like String variable, file or any network. ObjectMapper is most important class which acts as codec or data binder. ObjectMapper can write java object into JSON file and read JSON file into java Object. Jackson provides faster Streaming API i.e JsonParser and JsonGenerator. JsonParser reads JSON file and JsonGenerator writes java object or map into JSON file using coded object. While creating java class to map to and from JSON we must keep a default constructor because Jackson API creates java class instance using default constructor. 
Here we will cover below points.

Gradle file to Resolve Jackson JAR Dependency

Find the Gradle file to resolve Jackson JAR dependency in our project. 
build.gradle

apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'Concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
   compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.13'
}  

Create JSON as String by Object using ObjectMapper.writeValueAsString()

In Jackson JSON API org.codehaus.jackson.map.ObjectMapper is an important class. ObjectMapper is a codec or data binder that maps java object and JSON into each other. Here in this example we will convert java object into JSON string using writeValueAsString() method of ObjectMapper. 
CreateJSONWithObjectMapper.java

package com.concretepage;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class CreateJSONWithObjectMapper {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 ObjectMapper mapper = new ObjectMapper();
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 String json = mapper.writeValueAsString(person);
		 System.out.println(json);
	}
} 

Find the output.

{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}}

Find the class that will be used to convert into JSON and read JSON into Java object. Find the Address class. 
Address.java

package com.concretepage;
public class Address {
	private String village;
	private String district;
	private String state;
	public Address(){}
	public Address(String village, String district, String state){
		this.village = village;
		this.district = district;
		this.state = state;
	}
	public String getVillage() {
		return village;
	}
	public void setVillage(String village) {
		this.village = village;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
} 

Find the person class. 
Person.java

package com.concretepage;
public class Person {
	private Integer id; 
	private String name;
  	private Address address;
  	public Person(){}
  	public Person(Integer id, String name, Address address){
  		this.id = id;
  		this.name = name;
  		this.address = address;
  	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
} 

Write Object into JSON file using ObjectMapper.writeValue()

In this example, we will create a java object and using ObjectMapper.writeValue() method, we will convert that java object into JSON file. writeValue() serializes java object to JSON. 
WriteJSONWithObjectMapperOne.java

package com.concretepage;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class WriteJSONWithObjectMapperOne {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.writeValue(new File("D:/cp/dataOne.json"), person);
		 System.out.println("--Done--");
	}
}   

Find the output. 
dataOne.json

{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 

Pretty Print JSON using ObjectWriter with DefaultPrettyPrinter

Jackson API can write pretty print JSON . For that we can use DefaultPrettyPrinter instance. 
WriteJSONWithObjectMapperTwo.java

package com.concretepage;
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithObjectMapperTwo {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		 Person person = new Person(1, "Arvind", address);
		 ObjectMapper mapper = new ObjectMapper();
		 ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
		 writer.writeValue(new File("D:/cp/dataTwo.json"), person);
		 System.out.println("--Done--");
	}
}   

Find the output. 
dataTwo.json

{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 

Write java Map into JSON file using Jackson ObjectMapper

If we have data into map, that can also be converted into JSON using ObjectMapper. 
WriteJSONWithObjectMapperThree.java

package com.concretepage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithObjectMapperThree {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 Map<String,Object> person = new HashMap<String,Object>();
		 Map<String,String> address = new HashMap<String,String>();
		 address.put("Vill.", "Dhananjaypur");
		 address.put("Dist.", "Varanasi");
		 address.put("State", "UP");
		 person.put("id", "1");
		 person.put("name", "Arvind");
		 person.put("address", address);
		 ObjectMapper mapper = new ObjectMapper();
		 ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
		 writer.writeValue(new File("D:/cp/dataThree.json"), person);
		 System.out.println("--Done--");
	}
}   

Find the output. 
dataThree.json

{
  "address" : {
    "Vill." : "Dhananjaypur",
    "State" : "UP",
    "Dist." : "Varanasi"
  },
  "name" : "Arvind",
  "id" : "1"
} 

Read JSON file into Object using ObjectMapper.readValue()

To read JSON file into java object, Jackson provides ObjectMapper.readValue(). Find the input JSON file. 
dataOne.json

{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 

Now find the java class to read the JSON. 
ReadJSONWithObjectMapper.java

package com.concretepage;
import java.io.FileInputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
public class ReadJSONWithObjectMapper {
	public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException {
		 ObjectMapper mapper = new ObjectMapper();
		 mapper.configure(SerializationConfig.Feature.AUTO_DETECT_FIELDS, true);
		 //read from string variable
		 String json ="{\"id\":1,\"name\":\"Arvind\",\"address\":{\"village\":\"Dhananjaypur\",\"district\":\"Varanasi\",\"state\":\"UP\"}}";
		 Person person = mapper.readValue(json, Person.class);
		 System.out.println("Name:"+person.getName()+", Vill."+ person.getAddress().getVillage());
		 //Read from file
		 mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		 person = mapper.readValue(new FileInputStream("D:/cp/dataOne.json"), Person.class );
		 System.out.println("Name:"+person.getName()+", Vill."+ person.getAddress().getVillage());

	}
}

Find the output.

Name:Arvind, Vill.Dhananjaypur
Name:Arvind, Vill.Dhananjaypur

Write Object into JSON file using JsonGenerator

org.codehaus.jackson.JsonGenerator writes JSON using codec. To use JsonGenerator we can set codec as ObjectMapper() instance. In this example we will convert java object into JSON file. 
WriteJSONWithJsonGeneratorOne.java

package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
public class WriteJSONWithJsonGeneratorOne {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoOne.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		Person person = new Person(1, "Arvind", address);
		jsonGen.setCodec(new ObjectMapper());
		jsonGen.writeObject(person);
		System.out.println("Done");
	}
} 

Find the output. 
infoOne.json

{"id":1,"name":"Arvind","address":{"village":"Dhananjaypur","district":"Varanasi","state":"UP"}} 

Pretty Print using JsonGenerator

For pretty printing, Jackson provides DefaultPrettyPrinter that can be set to JsonGenerator instance. 
WriteJSONWithJsonGeneratorTwo.java

package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithJsonGeneratorTwo {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoTwo.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		Address address = new Address("Dhananjaypur", "Varanasi", "UP");
		Person person = new Person(1, "Arvind", address);
		jsonGen.setCodec(new ObjectMapper());
		jsonGen.setPrettyPrinter(new DefaultPrettyPrinter());
		jsonGen.writeObject(person);
		System.out.println("Done");
	}
} 

Find the output. 
infoTwo.json

{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 

Write java map into JSON file using JsonGenerator

Java map can be converted into JSON file using JsonGenerator. 
WriteJSONWithJsonGeneratorThree.java

package com.concretepage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.util.DefaultPrettyPrinter;
public class WriteJSONWithJsonGeneratorThree {
	public static void main(String[] args) throws IOException {
		JsonFactory jsonFactory = new JsonFactory(); 
		FileOutputStream file = new FileOutputStream(new File("D:/cp/infoThree.json"));
		JsonGenerator jsonGen = jsonFactory.createJsonGenerator(file, JsonEncoding.UTF8);
		jsonGen.setPrettyPrinter(new DefaultPrettyPrinter());
		jsonGen.writeStartObject();
		jsonGen.writeNumberField("id", 1);
		jsonGen.writeStringField("country", "India");
		jsonGen.writeFieldName("states");
		jsonGen.writeStartArray();
		jsonGen.writeString("UP");
		jsonGen.writeString("MP");
		jsonGen.writeEndArray();
		jsonGen.writeEndObject();
		jsonGen.close();
		System.out.println("Done");
	}
} 

Find the output. 
infoThree.json

{
  "id" : 1,
  "country" : "India",
  "states" : [ "UP", "MP" ]
} 

Read JSON file using JsonParser and JsonNode

org.codehaus.jackson.JsonParser reads JSON file. JsonParser can read JSON as tree returning JsonNode. Find the input JSON file. 
infoTwo.json

{
  "id" : 1,
  "name" : "Arvind",
  "address" : {
    "village" : "Dhananjaypur",
    "district" : "Varanasi",
    "state" : "UP"
  }
} 

Now find the java class to read the JSON. 
ReadJSONWithJsonParser.java

package com.concretepage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;
public class ReadJSONWithJsonParser {
	public static void main(String[] args) throws JsonParseException, IOException {
		JsonFactory jsonFactory = new JsonFactory();
		JsonParser jp = jsonFactory.createJsonParser(new File("D:/cp/infoTwo.json"));
		jp.setCodec(new ObjectMapper());
		JsonNode jsonNode = jp.readValueAsTree();
		readJsonData(jsonNode);
	}
	static void readJsonData(JsonNode jsonNode) {
		Iterator<Map.Entry<String, JsonNode>> ite = jsonNode.getFields();
		while(ite.hasNext()){
			Map.Entry<String, JsonNode> entry = ite.next();
			if(entry.getValue().isObject()) {
				readJsonData(entry.getValue());
			} else {
			    System.out.println("key:"+entry.getKey()+", value:"+entry.getValue());
			}
		}
	}
} 

Find the output.

key:id, value:1
key:name, value:"Arvind"
key:village, value:"Dhananjaypur"
key:district, value:"Varanasi"
key:state, value:"UP" 








3. 필요한 부분만 잘설명 되어있다

 http://noritersand.tistory.com/240

----------------------------------------------------------------------------------------------------------------------------------------

SON 문자열을 Map 이나 List Object 로 변환하는 것이랑

JSON 문자열을 xml 다루듯이 트래버싱 하는것,

Map 이나 List Object 를 JSON 문자열로 변환하는것  요래 정리를 해 보았다.

뭐 요정도만 알면 대충 할 수 있는건 다 할 수 있을듯하다. 뭐 필요하면 더 그때가서 더 찾아보면 되긋지~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package test;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
 
public class Test {
 
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        // 테스트 데이터 : 맵에 string 2개랑 list 하나가 들어가 있는 형태
        List<String> list = new ArrayList<String>();
        list.add("list1");
        list.add("list2");
        list.add("list3");
 
        Map<String, Object> d = new HashMap<String, Object>();
        d.put("list", list);
        d.put("a", "va");
        d.put("b", "vb");
        ////////////////////////////////////////////////
         
         
         
        ObjectMapper om = new ObjectMapper();
         
        // Map or List Object 를 JSON 문자열로 변환
        String jsonStr = om.writeValueAsString(d);
        System.out.println("object to json : " + jsonStr);
 
         
        // JSON 문자열을 Map or List Object 로 변환
        Map<String, Object> m = om.readValue(jsonStr, new TypeReference<Map<String, Object>>(){});
        System.out.println("json to object : " + m);
         
         
        // JSON 문자열을 xml 다루는것과 비슷하게 트리로 맨들어서 트래버싱하기(Tree Model)
        JsonNode root = om.readTree(jsonStr);
         
        // 단일값 가져오기
        System.out.println("b의 값 : " + root.path("b").getValueAsText());
         
        // 배열에 있는 값들 가져오기
        if( root.path("list").isArray() ){
            Iterator<jsonnode> it = root.path("list").iterator();
             
            // 요래 해도 됨
            // Iterator<jsonnode> it = root.path("list").getElements()
            while(it.hasNext()){
                System.out.println(it.next().getTextValue());
            }
        }
         
        // 이외 getXXXValue() 시리즈, findParent(), findValue() 등등 유용한 함수 많음~
    }
}

 Test.java













반응형