자바의 잭슨 프레임워크는 JSON을 쉽게 변환할 수 있습니다.
json-lib 프레임워크에 비해 잭슨이 의존하는jar 패키지는 비교적 적고 간단하며 사용하기 쉬우며 성능도 상대적으로 높다.게다가 잭슨 커뮤니티는 상대적으로 활발하고 업데이트 속도도 빠르다.
1. 준비 작업
1. 의존 라이브러리jar 패키지 다운로드
잭슨의 jar all 다운로드 주소:http://jackson.codehaus.org/1.7.6/jackson-all-1.7.6.jar
그리고 프로젝트에서 이jar 패키지를 가져오면 작업을 시작할 수 있습니다.
공식 예시:http://wiki.fasterxml.com/JacksonInFiveMinutes
다음 프로그램은 Junit 테스트 용례로 실행되기 때문에 Junit의jar 패키지를 추가해야 합니다.버전은 Junit-4.28입니다.
만약 당신이 xml을 변환해야 한다면, stax2-api가 필요합니다.jar
2. 테스트 클래스의 기본 코드는 다음과 같다.
package com.hoo.test;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.codehaus.jackson.xml.XmlMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.hoo.entity.AccountBean;
/**
* <b>function:</b>Jackson java JSON , JSON java
* jar-lib-version: jackson-all-1.6.2
* jettison-1.0.1
* @author hoojo
* @file JacksonTest.java
* @package com.hoo.test
* @project Spring3
* @version 1.0
*/
@SuppressWarnings("unchecked")
public class JacksonTest {
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private AccountBean bean = null;
@Before
public void init() {
bean = new AccountBean();
bean.setAddress("china-Guangzhou");
bean.setEmail("[email protected]");
bean.setId(1);
bean.setName("hoojo");
objectMapper = new ObjectMapper();
try {
jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
} catch (IOException e) {
e.printStackTrace();
}
}
@After
public void destory() {
try {
if (jsonGenerator != null) {
jsonGenerator.flush();
}
if (!jsonGenerator.isClosed()) {
jsonGenerator.close();
}
jsonGenerator = null;
objectMapper = null;
bean = null;
System.gc();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 필요한 JavaEntity
package com.hoo.entity;
public class AccountBean {
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
//getter、setter
@Override
public String toString() {
return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;
}
}
Birthday
package com.hoo.entity;
public class Birthday {
private String birthday;
public Birthday(String birthday) {
super();
this.birthday = birthday;
}
//getter、setter
public Birthday() {}
@Override
public String toString() {
return this.birthday;
}
}
2. Java 객체를 JSON으로 변환1. JavaBean(Entity/Model)을 JSON으로 변환
/**
* function: java json
* @author hoojo
*/
@Test
public void writeEntityJSON() {
try {
System.out.println("jsonGenerator");
//writeObject java ,eg:JavaBean/Map/List/Array
jsonGenerator.writeObject(bean);
System.out.println();
System.out.println("ObjectMapper");
//writeValue writeObject
objectMapper.writeValue(System.out, bean);
} catch (IOException e) {
e.printStackTrace();
}
}
실행 후 결과는 다음과 같습니다.
jsonGenerator
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"}
ObjectMapper
{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":[email protected]}
위에서 JsonGenerator의 writeObject 방법과 ObjectMapper의 writeValue 방법을 이용하여 자바 대상에 대한 전환을 완성했는데 양자가 전달하는 매개 변수와 구조의 방식이 다르다.JsonGenerator 생성은 ObjectMapper 객체에 의존합니다.즉, JSONGenerator를 사용하여 JSON을 변환하려면 ObjectMapper를 만들어야 합니다.하지만 Object Mapper로 JSON을 변환하려면 JSON Generator가 필요하지 않습니다.objectMapper의 writeValue 방법은 자바 대상을 JSON으로 변환할 수 있습니다.이 방법의 매개 변수는 하나, 출력 흐름을 제공해야 하며, 변환된 후에 이 흐름을 통해 변환된 내용을 출력할 수 있다.또는 변환된 내용을 파일에 기록하는 파일을 제공합니다.물론 이 매개 변수는 JSONGenerator를 수신한 다음 JSONGenerator를 통해 변환된 정보를 출력할 수 있습니다.두 번째 매개변수는 변환될 Java 객체입니다.세 가지 매개변수 방법을 사용하는 경우 Config입니다.이 config는 지정한 자바 대상의 일부 속성을 필터링하거나 변환하는 등 변환할 때의 규칙을 제공할 수 있습니다.
2. 맵 컬렉션을 Json 문자열로 변환
/**
* <b>function:</b> map json
* @author hoojo
*/
@Test
public void writeMapJSON() {
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", bean.getName());
map.put("account", bean);
bean = new AccountBean();
bean.setAddress("china-Beijin");
bean.setEmail("[email protected]");
map.put("account2", bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(map);
System.out.println("");
System.out.println("objectMapper");
objectMapper.writeValue(System.out, map);
} catch (IOException e) {
e.printStackTrace();
}
}
변환 후 결과는 다음과 같습니다.
jsonGenerator
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"[email protected]"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"}}
objectMapper
{"account2":{"address":"china-Beijin","name":null,"id":0,"birthday":null,"email":"[email protected]"},"name":"hoojo",
"account":{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":[email protected]}}
3. List 컬렉션을 json으로 변환
/**
* <b>function:</b> list json
* @author hoojo
*/
@Test
public void writeListJSON() {
try {
List<AccountBean> list = new ArrayList<AccountBean>();
list.add(bean);
bean = new AccountBean();
bean.setId(2);
bean.setAddress("address2");
bean.setEmail("email2");
bean.setName("haha2");
list.add(bean);
System.out.println("jsonGenerator");
//list JSON
jsonGenerator.writeObject(list);
System.out.println();
System.out.println("ObjectMapper");
// objectMapper list JSON
System.out.println("1###" + objectMapper.writeValueAsString(list));
System.out.print("2###");
//objectMapper list JSON
objectMapper.writeValue(System.out, list);
} catch (IOException e) {
e.printStackTrace();
}
}
결과는 다음과 같습니다.
jsonGenerator
[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
ObjectMapper
1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"[email protected]"},
{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
밖에 중괄호가 하나 더 있다.마찬가지로 Array도 변환할 수 있습니다. 변환된 JSON은 위의 결과와 같습니다. 여기는 더 이상 변환되지 않습니다. ~~4. 다음은 jackson이 제공하는 몇 가지 유형을 살펴보고 이런 유형으로 json 변환을 완성한다.이러한 유형의 JSON 변환을 사용하면 JavaBean (Entity) 이 없어도 복잡한 Java 유형의 JSON 변환을 완성할 수 있습니다.다음은 이러한 유형을 사용하여 복잡한 Java 객체를 구축하고 JSON 변환을 완료합니다.
@Test
public void writeOthersJSON() {
try {
String[] arr = { "a", "b", "c" };
System.out.println("jsonGenerator");
String str = "hello world jackson!";
//byte
jsonGenerator.writeBinary(str.getBytes());
//boolean
jsonGenerator.writeBoolean(true);
//null
jsonGenerator.writeNull();
//float
jsonGenerator.writeNumber(2.2f);
//char
jsonGenerator.writeRaw("c");
//String
jsonGenerator.writeRaw(str, 5, 10);
//String
jsonGenerator.writeRawValue(str, 5, 5);
//String
jsonGenerator.writeString(str);
jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
System.out.println();
//Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectFieldStart("user");//user:{
jsonGenerator.writeStringField("name", "jackson");//name:jackson
jsonGenerator.writeBooleanField("sex", true);//sex:true
jsonGenerator.writeNumberField("age", 22);//age:22
jsonGenerator.writeEndObject();//}
jsonGenerator.writeArrayFieldStart("infos");//infos:[
jsonGenerator.writeNumber(22);//22
jsonGenerator.writeString("this is array");//this is array
jsonGenerator.writeEndArray();//]
jsonGenerator.writeEndObject();//}
AccountBean bean = new AccountBean();
bean.setAddress("address");
bean.setEmail("email");
bean.setId(1);
bean.setName("haha");
//complex Object
jsonGenerator.writeStartObject();//{
jsonGenerator.writeObjectField("user", bean);//user:{bean}
jsonGenerator.writeObjectField("infos", arr);//infos:[array]
jsonGenerator.writeEndObject();//}
} catch (Exception e) {
e.printStackTrace();
}
}
실행 후 결과는 다음과 같습니다.
jsonGenerator
"aGVsbG8gd29ybGQgamFja3NvbiE=" true null 2.2c world jac worl "hello world jackson!" "hello world jackson!"
{"user":{"name":"jackson","sex":true,"age":22},"infos":[22,"this is array"]}
{"user":{"address":"address","name":"haha","id":1,"birthday":null,"email":"email"},"infos":["a","b","c"]}
어때요?구성된 json 문자열과 출력의 결과는 일치하죠.관건은 JSONGenerator가 제공한 방법으로 하나의 Object 구축을 완성하는 것이다.3. JSON을 Java 객체로 변환
1. json 문자열을 JavaBean 객체로 변환
@Test
public void readJson2Entity() {
String json = "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}";
try {
AccountBean acc = objectMapper.readValue(json, AccountBean.class);
System.out.println(acc.getName());
System.out.println(acc);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
간단합니다. ObjectMapper라는 대상의readValue를 사용했습니다. 이 방법은 2개의 인자를 제공해야 합니다.첫 번째 매개 변수는 해석된 JSON 문자열이고, 두 번째 매개 변수는 이 JSON을 어떤 Java 대상, Java 대상의 유형으로 해석할 것인지입니다.물론 같은 서명 방법도 있습니다. 관심이 있다면 일일이 방법을 시도해 보세요. 물론 사용하는 방법은 현재 사용하는 방법과 대동소이합니다.실행 후 결과는 다음과 같습니다.
haha
haha#1#address#null#email
2. json 문자열을 List
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Jackson 라이브러리해당 어노테이션을 사용하면 필드의 직렬화 대상을 설정할 수 있습니다. 현재 myAsset은 private입니다. 따라서 접근 할 수 없습니다. 하지만 fieldVisibility값을 Any로 준다면 private 속...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.