fastjson解析工具
Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式(序列化),当然它也可以将 JSON 字符串转换为 Java 对象(反序列化)。
JSON类的相关方法:
public static String toJSONString(Object object) :Java对象转Json字符串public static <T> T parseObject(String text, Class<T> clazz) :Json字符串转Java对象public static <T> List<T> parseArray(String text, Class<T> clazz) :Json字符串转换为集合对象,并指定集合的泛型;
实体类:
public class User {
private Integer id;
private String username;
private Integer age;
private String address;
}
1.1 对象与Json转换
package com.dfbz.json;
import com.alibaba.fastjson.JSON;
import com.dfbz.entity.User;
import org.junit.Test;
public class Demo01_FastJson_Obj_Str {
@Test
public void test1() {
User user = new User(1, "张三", 20, "山东青岛");
String jsonUser = JSON.toJSONString(user);
System.out.println(jsonUser);
}
@Test
public void test2() {
String json = "{\"address\":\"山东青岛\",\"age\":20,\"id\":1,\"username\":\"张三\"}";
User user = JSON.parseObject(json, User.class);
System.out.println(user);
}
@Test
public void test31(){
Map map=new HashMap();
map.put("id",1);
map.put("username","李四");
map.put("age",30);
map.put("address","广西贵港");
String jsonStr = JSON.toJSONString(map);
System.out.println(jsonStr);
}
@Test
public void test4(){
String jsonStr ="{\"address\":\"广西贵港\",\"id\":1,\"age\":30,\"username\":\"李四\"}";
Map map = JSON.parseObject(jsonStr, Map.class);
System.out.println(map);
}
}
1.2 集合与Json的转换
package com.dfbz.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.dfbz.entity.User;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Demo02_FastJson_Array_Json {
@Test
public void test1() {
List<User> userList = new ArrayList<>();
userList.add(new User(1, "张三", 20, "辽宁葫芦岛"));
userList.add(new User(2, "李四", 26, "云南昆明"));
userList.add(new User(3, "王五", 28, "云南昆明"));
userList.add(new User(4, "王五", 28, "西藏阿里"));
String jsonList = JSON.toJSONString(userList);
System.out.println(jsonList);
}
@Test
public void test2() {
String json = "[{\"address\":\"辽宁葫芦岛\",\"age\":20,\"id\":1,\"username\":\"张三\"},{\"address\":\"云南昆明\",\"age\":26,\"id\":2,\"username\":\"李四\"},{\"address\":\"云南昆明\",\"age\":28,\"id\":3,\"username\":\"王五\"},{\"address\":\"西藏阿里\",\"age\":28,\"id\":4,\"username\":\"王五\"}]";
List<User> userList = JSON.parseArray(json, User.class);
System.out.println(userList);
}
@Test
public void test3() {
String json = "[{\"demo\":\"123\"}]";
List<Map<String,Object>> list= JSON.parseObject(json, new TypeReference<List<Map<String,Object>>>(){});
System.out.println(list);
}
}
1.3 JSONObject对象
JSONObject是FastJson包提供的用来描述一个JSON字符串的对象,实现与Map接口,并且是JSON类的子类,本质上就是一个Map集合;JSONObject可以转换为Java对象,也可以转换为Json字符串;功能强大灵活
-
JSON类的方法:
public static JSONObject parseObject(String text) :Json字符串转换为JSONObject对象public static Object toJSON(Object javaObject) :将Java对象转换为JSONObject对象; -
JSONObject类的方法:
public <T> T toJavaObject(Class<T> clazz) :将JSONObject对象转换为对应的Java对象;public String toJSONString() :将JSONObject转换为Json字符串;
示例代码:
package com.dfbz.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dfbz.entity.User;
import org.junit.Test;
public class Demo03_JSONObject {
@Test
public void test1() throws Exception{
User user = new User(1, "王五", 28, "云南昆明");
JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
System.out.println(jsonObject);
}
@Test
public void test2() throws Exception{
String jsonStr="{\"address\":\"云南昆明\",\"id\":1,\"age\":28,\"username\":\"王五\"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
System.out.println(jsonObject);
}
@Test
public void test3() throws Exception{
String jsonStr="{\"address\":\"云南昆明\",\"id\":1,\"age\":28,\"username\":\"王五\"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
User user = jsonObject.toJavaObject(User.class);
System.out.println(user);
}
@Test
public void test4() throws Exception{
String jsonStr="{\"address\":\"云南昆明\",\"id\":1,\"age\":28,\"username\":\"王五\"}";
JSONObject jsonObject = JSON.parseObject(jsonStr);
String str = jsonObject.toJSONString();
System.out.println(str);
}
}
1.4 SerializerFeature
SerializerFeature是一个枚举类,用于设置Json转换时相关的参数
属性 | 介绍 |
---|
QuoteFieldNames | 输出key时是否使用双引号,默认为true | UseSingleQuotes | 使用单引号而不是双引号,默认为false | WriteMapNullValue | 是否输出值为null的字段,默认为false | WriteEnumUsingToString | Enum输出name()或者original,默认为false | UseISO8601DateFormat | Date使用ISO8601格式输出,默认为false | WriteNullListAsEmpty | List字段如果为null,输出为[],而非null | WriteNullStringAsEmpty | 字符类型字段如果为null,输出为”“,而非null | WriteNullNumberAsZero | 数值字段如果为null,输出为0,而非null | WriteNullBooleanAsFalse | Boolean字段如果为null,输出为false,而非null | SkipTransientField | 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true | SortField | 按字段名称排序后输出,默认为false | WriteTabAsSpecial | 把\t做转义输出,默认为false 不推荐 | PrettyFormat | 结果是否格式化,默认为false | WriteClassName | 序列化时写入类型信息,默认为false。反序列化是需用到 | DisableCircularReferenceDetect | 消除对同一对象循环引用的问题,默认为false | WriteSlashAsSpecial | 对斜杠’/’进行转义 | BrowserCompatible | 将中文都会序列化为\uXXXX格式,字节数会多一些,但是能兼容IE 6,默认为false | WriteDateUseDateFormat | 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat); | DisableCheckSpecialChar | 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。 如果不需要转义,可以使用这个属性,默认为false | BeanToArray | 将对象转为array输出 |
public class TestEntity {
private String id;
private String name;
private Integer age;
private Boolean flag;
private Date date;
private User user;
}
package com.dfbz.json;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dfbz.entity.TestEntity;
import com.dfbz.entity.User;
import org.junit.Test;
import java.util.Date;
public class Demo04_FastJson_SerializerFeature {
@Test
public void test() {
User user = new User(1, "老王", null, "江西新余");
TestEntity testEntity = new TestEntity("1", null, null, null, new Date(), user);
String jsonStr = JSON.toJSONString(testEntity);
System.out.println(jsonStr);
JSON.DEFFAULT_DATE_FORMAT = "yyyy年MM月dd日";
String jsonStr2 = JSON.toJSONString(
testEntity,
SerializerFeature.UseSingleQuotes,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.BeanToArray,
SerializerFeature.PrettyFormat
);
System.out.println(jsonStr2);
}
}
1.5 FastJson常用注解
@JSONField :
ordinal :序列化时的顺序,数值越小越靠前;name :序列化时的名称format :指定转换日期时的格式serialize :是否要序列化,默认truedeserialize :是否要反序列化,默认trueserialzeFeatures :指定序列化时的一些特性
public class Emp {
@JSONField(name = "empId", ordinal = 1,defaultValue = "100")
private Integer id;
@JSONField(ordinal = 3,deserialize = false)
private String username;
@JSONField(ordinal = 2, serialize = false)
private Integer age;
@JSONField(ordinal = 4, format = "yyyy-MM-dd HH:mm:ss")
private Date birthday;
@JSONField(ordinal = 5,serialzeFeatures = SerializerFeature.WriteNullBooleanAsFalse)
private Boolean flag;
}
package com.dfbz.json;
import com.alibaba.fastjson.JSON;
import com.dfbz.entity.Emp;
import org.junit.Test;
import java.util.Date;
public class Demo05_FastJson_Annotation {
@Test
public void test() {
Emp emp = new Emp(1, "张三", 20, new Date(),null);
String jsonStr = JSON.toJSONString(emp);
System.out.println(jsonStr);
Emp emp2 = JSON.parseObject(jsonStr, Emp.class);
System.out.println(emp2);
}
}
@JSONType :
orders :序列化时的顺序includes :只序列化那些字段ignores :不序列化那些字段
@JSONType(
orders = {"flag","id","username","age","birthday"},
ignores = {"age","birthday"}
)
public class Account {
private Integer id;
private String username;
private Integer age;
private Date birthday;
private Boolean flag;
}
@Test
public void test2() {
Account account = new Account(1, "张三", 20, new Date(),null);
String jsonStr = JSON.toJSONString(account);
System.out.println(jsonStr);
}
|