"name" : "阿狗"
可以是:
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FastJSONTest {
public static void main(String[] args) {
//将map转成JSON对象
Map<String,Object> map1 = new HashMap<String, Object>();
map1.put("k1","one");
map1.put("k2","two");
String mapJson = JSON.toJSONString(map1);
System.out.println(mapJson);
//将list转成JSON对象
List
结果:
{"k1":"one","k2":"two"}
[{"k1":"one","k2":"two"},{"k1":"Three","k2":"Four"}]
{"cities":["太原","大同"],"name":"山西"}
[
{
"k1":"one",
"k2":"two"
},
{
"k1":"Three",
"k2":"Four"
}
]
String objJson = JSON.toJSONString(Object object, SerializerFeature... features)
传入一个对象和SerializerFeature类型的可变变量。SerializerFeature是一个枚举。
com.alibaba.fastjson.serializer.SerializerFeature
//日期格式化
//FastJSON可以直接对日期类型格式化,在缺省的情况下,FastJSON会将Date转成long。
String dateJson1 = JSON.toJSONString(new Date());
System.out.println(dateJson1);
//使用SerializerFeature特性格式化日期。
String dateJson2 = JSON.toJSONString(new Date(), SerializerFeature.WriteDateUseDateFormat);
System.out.println(dateJson2);
//指定输出日期格式
String dateJson3 = JSON.toJSONStringWithDateFormat(new Date(),"yyyy-MM-dd HH:mm:ss");
System.out.println(dateJson3);
//使用单引号
String listJson2 = JSON.toJSONString(list,SerializerFeature.UseSingleQuotes);
System.out.println(listJson2);
//JSON格式化
String listJsonFormat1 = JSON.toJSONString(list,SerializerFeature.PrettyFormat);
System.out.println(listJsonFormat1);
//输出Null字段
//缺省情况下FastJSON不输入为值Null的字段,可以使用SerializerFeature.WriteMapNullValue使其输出。
Map<String,Object> map3 = new HashMap<String, Object>();
String b=null;
Integer i = 1;
map3.put("a",b);
map3.put("b",i);
String listJson4 = JSON.toJSONString(map3,SerializerFeature.WriteMapNullValue);
System.out.println(listJson4);
//序列化要写入类型信息。
Shengshi sshi1 =new Shengshi();
sshi1.setName("山西");
ArrayList<String> cities1 = new ArrayList<String>();
cities1.add("太原");
cities1.add("大同");
sshi1.setCities(cities1);
String sshiJson1 = JSON.toJSONString(sshi,SerializerFeature.WriteClassName,SerializerFeature.PrettyFormat);
System.out.println(sshiJson1);
//反序列化(由于序列化带了类型信息,使得反序列化时能够自动进行类型识别。)
Shengshi sshi2 = (Shengshi)JSON.parse(sshiJson1);
System.out.println(sshi2.toString());
结果:
1534257943343
"2018-08-14 22:45:43"
"2018-08-14 22:45:43"
[{'k1':'one','k2':'two'},{'k1':'Three','k2':'Four'}]
[
{
"k1":"one",
"k2":"two"
},
{
"k1":"Three",
"k2":"Four"
}
]
{"a":null,"b":1}
{
"@type":"Shengshi",
"cities":[
"太原",
"大同"
],
"name":"山西"
}
Shengshi{name='山西', cities=[太原, 大同]}
//集合反序列化
List list1 = JSON.parseArray(listJson,Map.class);
for (Mapmap:list1)
{
System.out.println(map.get("k1"));
System.out.println(map.get("k2"));
}
//泛型的反序列化(使用TypeReference传入类型信息)。
Map map4 = JSON.parseObject(mapJson,new TypeReference>(){});
System.out.println(map4.get("k1"));
System.out.println(map4.get("k2"));
结果:
one
two
Three
Four
one
two