<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.15</version>
</dependency>
代码:
package com.geo.testfastjson;
public class User {
private int id;
private String name;
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;
}
}
package com.geo.testfastjson;
public class Weibo {
private String id;
private String city;
public Weibo(String id, String city) {
this.id = id;
this.city = city;
}
public Weibo() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
package com.geo.testfastjson;
import java.util.ArrayList;
import java.util.List;
public class Group {
private int id;
private String name;
private List<User> list = new ArrayList<User>();
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 List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
}
package com.geo.testfastjson;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.geo.testGson.TestGsonJiexi2;
public class JsonDemo {
//下面是FastJson的简介:常用的方法!
// Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。
// public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
// public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
// public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
// public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
// public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
// public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
// public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
// public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray(和上面方法的区别是返回值是不一样的)
/**
* 这是关于FastJson的一个使用Demo,在Java环境下验证的;
* 使用的时候可以参照这个例子进行回忆!
* 备注:下面写的Json格式的数据"前面的,意思是告诉编译器忽略掉它后面的"。
* 后面定义有三个类:User、Group、Weibo
* @author liuzhao
*/
public static void main(String[] args) {
json2JSONArrayM3();//将json数据转化为JSONArray:
toBeanMethod();//将复杂json数据转为bean
/*json2JsonObjectM1();//将Json文本数据信息转换为JsonObject对象,然后利用键值对的方式获取信息
json2BeanM2();//将Json文本数据转换为JavaBean数据!
json2JSONArrayM3();//将json数据转化为JSONArray:
json2JavaBeanM4();//将JSON文本转换为JavaBean的集合;转换为单纯的1个Object:parseObject(String text, Class<T> clazz);
bean2JsonM5();//将JavaBean转换为Json格式的数据/Json文本 用户数据的传递:例如上传服务器
bean2JSONObjectM6();//将JavaBean转换为JSON对象
complexExampleM7();//一个相对复杂的例子:
complex2JsonM8();//一个复杂的Object到Json的Demo
complexMap2JsonM9();//将Map数据转换为JsonString的Demo;这个对RedBoy服务端不就直接破了嘛!
*/
}
//将复杂json数据转为bean
public static void toBeanMethod(){
String json = "{"a":"100","b":[{"b1":"b_value1","b2":"b_value2"}, {"b1":"b_value1","b2":"b_value2"}],"c": {"c1":"c_value1","c2":"c_value2"}}";
TestGsonJiexi2 testGsonJiexi2bean = JSON.parseObject(json, TestGsonJiexi2.class);
System.out.println("a:"+testGsonJiexi2bean.getA()+" b[0].b1:"+testGsonJiexi2bean.getB().get(0).getB1());
}
/**
* 将Json文本数据信息转换为JsonObject对象,然后利用键值对的方式获取信息
*/
private static void json2JsonObjectM1() {
//一个JsonObject文本数据
String s = "{"name":"liuzhao"}";
//将JsonObject数据转换为Json
JSONObject object = JSON.parseObject(s);
//利用键值对的方式获取到值
System.out.println(object.get("name"));
/**
* 打印:
* liuzhao
*/
}
/**
* 将Json文本数据转换为JavaBean数据!
* 需要注意的是:这时候的Json文本信息中的键的名称必须和JavaBean中的字段名称一样!键中没有的在这个JavaBean中就显示为null!
*/
private static void json2BeanM2() {
String s = "{"id":"0375","city":"平顶山"}";
//一个简单方便 的方法将Json文本信息转换为JsonObject对象的同时转换为JavaBean对象!
Weibo weibo = JSON.parseObject(s, Weibo.class);//Weibo类在下边定义
System.out.println(weibo.getId());
System.out.println(weibo.getCity());
//打印的结果 0375
// 平顶山
}
/**
* 将Map类型的数据转换为JsonString
*/
private static void complexMap2JsonM9() {
Group group = new Group();
group.setId(1);
group.setName("group");
User user1 = new User();
user1.setId(2);
user1.setName("user1");
User user2 = new User();
user2.setId(3);
user2.setName("user2");
group.getList().add(user1);
group.getList().add(user2);
Map<Integer, Object> map = new HashMap<Integer,Object>();
map.put(1, "No.1");
map.put(2, "No.2");
map.put(3, group.getList());
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);
/**
* 输出:{1:"No.1",2:"No.2",3:[{"id":2,"name":"user1"},{"id":3,"name":"user2"}]}
*/
}
/**
* 由一个复杂的Object到Json的Demo
*/
private static void complex2JsonM8() {
Group group = new Group();
group.setId(1);
group.setName("group");
User user1 = new User();
user1.setId(2);
user1.setName("user1");
User user2 = new User();
user2.setId(3);
user2.setName("user2");
group.getList().add(user1);
group.getList().add(user2);
String jsonString = JSON.toJSONString(group);
System.out.println(jsonString);
/**
* 输出:{"id":1,"list":[{"id":2,"name":"user1"},{"id":3,"name":"user2"}],"name":"group"}
*/
}
/**
* 一个相对复杂的例子:
* JSON文本数据:
* 首先是JSONObject,转换为JSONArray;
* 然后将JSONArray转换为JavaBean
*/
private static void complexExampleM7() {
String s = "{js:[{id:"110000","city":"北#001京市"},{id:"110000","city":"北#002京市"}"
+ ",{id:"110000","city":"北#002京市"},{id:"110000","city":"北#002京市"},"
+ "{id:"110000","city":"#006北#005京市"},"
+ "{id:"110000","city":"北#002京市"},"
+ "{id:"110000","city":"北#002京市"},{id:"120000","city":"天#009津市"}]}";
JSONObject object = JSON.parseObject(s);
Object jsonArray = object.get("js");
System.out.println(jsonArray);
List<Weibo> list = JSON.parseArray(jsonArray+"", Weibo.class);
for (Weibo weibo : list) {
System.out.println(weibo.getCity());
}
}
/**
* 将JavaBean转换为JSON对象
*/
private static void bean2JSONObjectM6() {
Weibo weibo = new Weibo("0373", "洛阳");
JSONObject json = (JSONObject) JSON.toJSON(weibo);
System.out.println(json.get("id"));
/**
* 打印:
* 0373
*/
}
/**
* 将JSON文本转换为JavaBean的集合;
* 内部实现肯定是:首先转换为JSONArray,然后再转换为List集合
*/
private static void json2JavaBeanM4() {
String s = "[{"id":"0375","city":"平顶山"},{"id":"0377","city":"南阳"}]";
List<Weibo> list = JSON.parseArray(s, Weibo.class);
for (Weibo weibo : list) {
System.out.println(weibo.getCity());
}
/**
* 打印:
* 平顶山
* 南阳
*/
}
/**
* 将json数据转化为JSONArray:
* 注意:获取到JSONArray之后(我们这里只是获取到JSONArray而不是JavaBean的List集合)
* 获取JSONArray中的数据转换为String类型需要在外边加"";
*/
private static void json2JSONArrayM3() {
String s = "[{"id":"0375","city":"平顶山"},{"id":"0377","city":"南阳"}]";
//将JSON文本转换为JSONArray
JSONArray array = JSON.parseArray(s);
String str = array.get(1)+"";//或 array.get(1).toString();
System.out.println(array.get(0));
JSONObject object = JSON.parseObject(str);
System.out.println(object.get("id"));
/**
* {"city":"平顶山","id":"0375"}
0377
*/
}
/**
* 将JavaBean转换为Json格式的数据/Json文本
* 用户数据的传递:例如上传服务器
*/
private static void bean2JsonM5() {
Weibo weibo = new Weibo("123456", "上海");
String string = JSON.toJSONString(weibo);
System.out.println(string);
/**
* 打印:
* {"city":"上海","id":"123456"}
*/
}
}
Gson解析的例子:
package com.geo.testGson;
import java.util.List;
import com.google.gson.Gson;
/**
* json 解析成对象
* @author DELL
*
*/
public class TestGsonJiexi2 {
public String a;
public String a1;
public List<B> b;
public C c;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public List<B> getB() {
return b;
}
public void setB(List<B> b) {
this.b = b;
}
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
public static class B {
public String b1;
public String b2;
public String getB1() {
return b1;
}
public void setB1(String b1) {
this.b1 = b1;
}
public String getB2() {
return b2;
}
public void setB2(String b2) {
this.b2 = b2;
}
}
public static class C {
public String c1;
public String c2;
public String getC1() {
return c1;
}
public void setC1(String c1) {
this.c1 = c1;
}
public String getC2() {
return c2;
}
public void setC2(String c2) {
this.c2 = c2;
}
}
@Override
public String toString() {
return "TestGsonJiexi2 [a=" + a + ", b=" + b + ", c=" + c + "]";
}
public static void main(String[] args) {
String json = "{"a":"100","b":[{"b1":"b_value1","b2":"b_value2"}, {"b1":"b_value1","b2":"b_value2"}],"c": {"c1":"c_value1","c2":"c_value2"}}";
Gson gson = new Gson();
/*java.lang.reflect.Type type = new TypeToken<TestGsonJiexi2>() {}.getType();
TestGsonJiexi2 TestGsonJiexi2Bean = gson.fromJson(json, type);
System.out.println(TestGsonJiexi2Bean.getA());*/
TestGsonJiexi2 TestGsonJiexi2Bean = gson.fromJson(json,TestGsonJiexi2.class); //
System.out.println("a:"+TestGsonJiexi2Bean.getA()+" b[0].b1:"+TestGsonJiexi2Bean.getB().get(0).getB1());
System.out.println("a1:"+TestGsonJiexi2Bean.getA1()+" "+(null == TestGsonJiexi2Bean.getA1())); //json中无a1的值,会映射为null
}
}
package com.geo.testGson;
public class Student {
private String name;
private String address;
private String dateOfBirth;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
@Override
public String toString() {
return "Student [address=" + address + ", dateOfBirth=" + dateOfBirth + ", name=" + name + "]";
}
}
package com.geo.testGson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* json 解析成对象
* @author DELL
*
*/
public class TestGsonJiexi {
//1、 解析JSON对象,将其还原为JavaBean,或者相应的数据类型
public static void method1(){
String json = "{"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}";//JSON格式的数据
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);//指定了要还原的class,保存在gson中。
System.out.println("student.getName() = " + student.getName());
System.out.println("student.getAddress() = " + student.getAddress());
System.out.println("student.getDateOfBirth() = "
+ student.getDateOfBirth());//可以直接从student对象中获取到所有数据了。
}
//如果Json对象本身是List形式的,或者其他的类型,则采用以下方法: 可以借助TypeToken获取泛型参数的类型。
public static void method2(){
String json = "[{"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}]";
Gson gson = new Gson();
//使用Type类,取得相应类型对象的class属性。
Type listType=new TypeToken<ArrayList<Student>>(){}.getType();//TypeToken内的泛型就是Json数据中的类型
ArrayList list = gson.fromJson(json, listType);//使用该class属性,获取的对象均是list类型的
System.out.println("student.getName() = " + ((Student) list.get(0)).getName());//从list中取得内容即可
System.out.println("student.getAddress() = " + ((Student) list.get(0)).getAddress());
System.out.println("student.getDateOfBirth() = "
+ ((Student) list.get(0)).getAddress());
}
public static void main(String[] args) {
method1();
}
}
from: http://www.voidcn.com/blog/zygzzp/article/p-5800467.html
http://www.360doc.com/content/14/1126/00/13147830_428094441.shtml