jackson 변환 json
8920 단어 Jackson
테스트 클래스:
package com.demo.test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.JsonNodeFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.demo.entity.Account;
public class JacksonTest {
private JsonGenerator jsonGenerator = null;
private ObjectMapper objectMapper = null;
private Account bean = null;
@Before
public void init() {
bean = new Account();
bean.setAddress("CHINA-BJ");
bean.setEmail("[email protected]");
bean.setId(1);
bean.setName("haha");
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;
} catch (Exception e) {
e.printStackTrace();
}
}
@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 (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void writeMapJson() {
try{
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", bean.getName());
map.put("account", bean);
bean = new Account();
bean.setAddress("CHINA-GZ");
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 (Exception e) {
e.printStackTrace();
}
}
@Test
public void writeListJson() {
try{
List<Account> accounts = new ArrayList<Account>();
accounts.add(bean);
bean = new Account();
bean.setId(2);
bean.setName("lala");
bean.setAddress("CHINA-GZ");
bean.setEmail("[email protected]");
accounts.add(bean);
System.out.println("jsonGenerator");
jsonGenerator.writeObject(accounts);
System.out.println();
System.out.println("objectMapper");
System.out.println("1###" + objectMapper.writeValueAsString(accounts));
System.out.println("2###");
objectMapper.writeValue(System.out, accounts);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void writeOthersJson() {
try{
String[] arr = {"abc", "def", "jhi"};
System.out.println("jsonGenerator");
String str = "Hello Jackson!";
//byte
jsonGenerator.writeBinary(str.getBytes());
//boolean
jsonGenerator.writeBoolean(true);
//null
jsonGenerator.writeNull();
//float
jsonGenerator.writeNumber(2.5f);
//char
jsonGenerator.writeRaw("c");
//String
jsonGenerator.writeRaw(str, 1, 5);
//String
jsonGenerator.writeRawValue(str, 5, 5);
//String
jsonGenerator.writeString(str);
jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str));
System.out.println();
//Objcet {"user":{"name":"lala","sex":true,"age":26},"infos":[22,"Hello Jackson"]}
jsonGenerator.writeStartObject(); //{
jsonGenerator.writeObjectFieldStart("user"); //user:{
jsonGenerator.writeStringField("name", "lala"); //name:lala
jsonGenerator.writeBooleanField("sex", true); // sex:true
jsonGenerator.writeNumberField("age", 26); // age:26
jsonGenerator.writeEndObject(); //}
//Array
jsonGenerator.writeArrayFieldStart("infos"); //infos:[
jsonGenerator.writeNumber(22); //22
jsonGenerator.writeString("Hello Jackson"); //Hello Jackson
jsonGenerator.writeEndArray(); //]
jsonGenerator.writeEndObject(); //}
// complex object
jsonGenerator.writeStartObject();
jsonGenerator.writeObjectField("account", bean);
jsonGenerator.writeObjectField("infos", arr);
jsonGenerator.writeEndObject();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void readJson2Entity() {
try{
String json = "{\"address\":\"SH\",\"name\":\"lala\",\"id\":1,\"email\":\"[email protected]\"}";
Account account = objectMapper.readValue(json, Account.class);
System.out.println(account.getName());
System.out.println(account);
}catch (Exception e) {
e.printStackTrace();
}
}
public void others() {
String json = "";
try {
//readJson2List
List<LinkedHashMap<String, Object>> list = objectMapper.readValue(json, List.class);
//readJson2Array
Account[] arr = objectMapper.readValue(json, Account[].class);
//readJson2Map
Map<String, Map<String, Object>> map = objectMapper.readValue(json, Map.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
객체:
package com.demo.entity;
import java.io.Serializable;
public class Account implements Serializable{
private static final long serialVersionUID = -5985853834387791596L;
private int id;
private String name;
private String email;
private String address;
private Birthday birthday;
public Account () {
super();
}
public Account(int id, String name, String email, String address,
Birthday birthday) {
super();
this.id = id;
this.name = name;
this.email = email;
this.address = address;
this.birthday = birthday;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", email=" + email
+ ", address=" + address + ", birthday=" + birthday + "]";
}
}
ps: 원래 인터넷에서 잭슨으로 xml을 쉽게 만들 수 있는 것을 보았는데 XmlMapper는 이미 잭슨-alljar 패키지에 존재하지 않아요. 네티즌들이 방법을 찾았어요. 그런데 저는 아직 시도하지 않아서 xml로 전환하는 테스트 방법이 없어요.
참조 자료:
http://www.cnblogs.com/hoojo/archive/2011/04/22/2024628.html
http://wiki.fasterxml.com/JacksonInFiveMinutes
http://blog.sina.com.cn/s/blog_9d0ce63d01012vmd.html
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
초보자가 Kotlin + Spring Boot의 Get 요청에서 JSON을 반환하기 위해 한 일업무로 서버측을 하게 되었으므로 그 연습을 위해 했던 일을 정리했습니다. 서버의 경험은 한순간 밖에 없습니다 🥺🥺🥺 (Java의 입문서를 해낸 정도... 먼저 @getMapping에서 String을 반환하는 방법은 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.