자바의 잭슨 프레임워크는 JSON을 쉽게 변환할 수 있습니다.

20506 단어 jacksonjson
잭슨은 자바 대상을 json 대상과 xml 문서로 쉽게 변환할 수 있고 json, xml을 자바 대상으로 변환할 수 있다.
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 컬렉션으로 변환

/**
 * <b>function:</b>json list<map>
 * @author hoojo
 */
@Test
public void readJson2List() {
  String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
        "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
  try {
    List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
    System.out.println(list.size());
    for (int i = 0; i < list.size(); i++) {
      Map<String, Object> map = list.get(i);
      Set<String> set = map.keySet();
      for (Iterator<String> it = set.iterator();it.hasNext();) {
        String key = it.next();
        System.out.println(key + ":" + map.get(key));
      }
    }
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

위의 JSON을 List로 변환하고 List에 AccountBean을 저장하려고 시도했지만 실패했습니다.하지만 맵 집합은 지원됩니다.너 때문에 리스트로 바뀌었어.class, 하지만 List가 어떤 종류를 저장하는지 알 수 없습니다.묵묵히 맵 유형을 설정할 수밖에 없습니다.모든 객체가 맵 결합으로 변환될 수 있으므로 실행 후 결과는 다음과 같습니다.

2
address:address2
name:haha2
id:2
email:email2
address:address
name:haha
id:1
email:email
3. Json 문자열은 Array 수조로 변환됩니다. 위의 범용 변환으로 인해 집합의 대상 유형을 식별할 수 없습니다.여기에 대상 수조를 사용하면 이 문제를 해결할 수 있다.단지 그것은 더 이상 집합이 아니라 하나의 수조일 뿐이다.물론 이것은 중요하지 않으니, 너는 Arrays를 사용할 수 있다.asList를 List로 변환하면 됩니다.

/**
 * <b>function:</b>json Array
 * @author hoojo
 */
@Test
public void readJson2Array() {
  String json = "[{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
      "{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}]";
  try {
    AccountBean[] arr = objectMapper.readValue(json, AccountBean[].class);
    System.out.println(arr.length);
    for (int i = 0; i < arr.length; i++) {
      System.out.println(arr[i]);
    }
    
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

실행 후 결과:

2
haha2#2#address2#null#email2
haha#1#address#null#email
4. Json 문자열을 맵 집합으로 변환

/**
 * <b>function:</b>json Map 
 * @author hoojo */
@Test
public void readJson2Map() {
  String json = "{\"success\":true,\"A\":{\"address\": \"address2\",\"name\":\"haha2\",\"id\":2,\"email\":\"email2\"},"+
        "\"B\":{\"address\":\"address\",\"name\":\"haha\",\"id\":1,\"email\":\"email\"}}";
  try {
    Map<String, Map<String, Object>> maps = objectMapper.readValue(json, Map.class);
    System.out.println(maps.size());
    Set<String> key = maps.keySet();
    Iterator<String> iter = key.iterator();
    while (iter.hasNext()) {
      String field = iter.next();
      System.out.println(field + ":" + maps.get(field));
    }
  } catch (JsonParseException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

실행 후 결과는 다음과 같습니다.

3
success:true
A:{address=address2, name=haha2, id=2, email=email2}
B:{address=address, name=haha, id=1, email=email}
넷째, XML에 대한 잭슨의 지원
잭슨도 자바 대상을 xml로 전환할 수 있다. 전환 후의 결과는 json-lib보다 직관적이지만 stax2-api에 의존한다.이거 가방

/**
 * <b>function:</b>java xml 
 *  jar  stax2-api.jar
 * @author hoojo
 */
@Test
public void writeObject2Xml() {
  //stax2-api-3.0.2.jar
  System.out.println("XmlMapper");
  XmlMapper xml = new XmlMapper();
  
  try {
    //javaBean xml
    //xml.writeValue(System.out, bean);
    StringWriter sw = new StringWriter();
    xml.writeValue(sw, bean);
    System.out.println(sw.toString());
    //List xml
    List<AccountBean> list = new ArrayList<AccountBean>();
    list.add(bean);
    list.add(bean);
    System.out.println(xml.writeValueAsString(list));
    
    //Map xml 
    Map<String, AccountBean> map = new HashMap<String, AccountBean>();
    map.put("A", bean);
    map.put("B", bean);
    System.out.println(xml.writeValueAsString(map));
  } catch (JsonGenerationException e) {
    e.printStackTrace();
  } catch (JsonMappingException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }
}

위의 방법을 실행한 결과 다음과 같습니다.

XmlMapper
<unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></unknown>
<unknown><unknown><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></unknown>
<email><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></email></unknown>
<unknown><A><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></A>
<B><address>china-Guangzhou</address><name>hoojo</name><id>1</id><birthday/><email>[email protected]</email></B></unknown>
그 결과 루트 노드가 unknown이라는 문제는 아직 해결되지 않았습니다. 루트 노드가 변환되지 않았기 때문에 xml을 자바 대상으로 해석해도 완성할 수 없습니다.
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기