1、jackson 框架:这个框架提供了JsonGenerator ,ObjectMapper两个类通过这两个类提供的方法可以将java 对象转化为json 对象,json 数组格式,也可以将json对象、数组格式转化为java对象。
2、json-lib框架也可以进行json格式和java 对象之间的相互转化,json-lib提供的类主要有:JSONObject ,JSONArray....
3、展现使用两种框架进行相互转化:
一、json-lib:
package com.inspur.json;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JSONTest {
public static void main(String[] args) {
User u = new User();
u.setName("name1");
u.setAge(1);
u.setPhone("123");
User u2 = new User();
u2.setName("name2");
u2.setAge(2);
u2.setPhone("321");
List list = new ArrayList();
list.add(u);
list.add(u2);
// 创建JSONObject 对象
JSONObject jobg = new JSONObject();
// 创建JSONObject 对象
JSONArray arr = new JSONArray();
// 将对象转化为json对象的格式
JSONObject str = jobg.fromObject(u);
// 将list集合转化为json数组的格式
JSONArray str1 = arr.fromObject(list);
System.out.print(str);
System.out.print("\n");
System.out.print(str1);
}
}
/* 运行结果 */
{"age":1,"name":"name1","phone":"123"}
[{"age":1,"name":"name1","phone":"123"},{"age":2,"name":"name2","phone":"321"}]
二、jackson框架提供的两个类 JsonGenerator ObjectMapper
package com.jackson.test;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
public class Test {
public static void main(String[] args) {
User u = new User();
u.setName("name1");
u.setAge(1);
u.setSex("man");
User u2 = new User();
u2.setName("name2");
u2.setAge(2);
u2.setSex("man");
List list = new ArrayList();
list.add(u);
list.add(u2);
ObjectMapper obj = new ObjectMapper();
JsonGenerator jg = null;
try {
jg = obj.getJsonFactory().createJsonGenerator(System.out,
JsonEncoding.UTF8);
System.out.println("jsonGenerator");
// writeObject可以转换java对象,eg:JavaBean/Map/List/Array等
jg.writeObject(u);
System.out.println();
jg.writeObject(list);
System.out.println();
System.out.println("ObjectMapper");
// writeValue具有和writeObject相同的功能
obj.writeValue(System.out, list);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/ * 运行结果 */
jsonGenerator
{"name":"name1","age":1,"sex":"man"}
[{"name":"name1","age":1,"sex":"man"},{"name":"name2","age":2,"sex":"man"}]
ObjectMapper
[{"name":"name1","age":1,"sex":"man"},{"name":"name2","age":2,"sex":"man"}]