JSON理解
簡稱:JavaScript Object Notation, JS標記对象
理解:是一種輕量級的,通用的數據交換格式,存儲方式類似于鍵值對(當然值中也能夠存儲鍵值對,這就導致了json中數據可以多層嵌套)
格式
1.以鍵值對的形式存儲:
{
"name":"小明",
"age":18,
"sex":"男"
}
2.值(屬性)也可以存儲對象
{
"name":"小明",
"age":18,
"sex":"男"
"school":{
"name":"UCLA",
"number":"299900",
"chief":"Andy"
}
}
3.Json存儲數組:
[123,456,789]
["ABC","DEF","GHI"]
4.还可以存储多个Json对象
[
{
"name":"小明",
"age":18,
"sex":"男"
},
{
"name":"小红",
"age":21,
"sex":"女"
},
{
"name":"小丽",
"age":16,
"sex":"女"
}
]
通过Gson和FastJson存储对象
1.通过Gson转化Json对象
import java.util.ArrayList;
import java.util.List;
public class Gson {
public static void main(String[] args) {
Person p1 = new Person("小明",16,"我很帥");
Person p2 = new Person("小紅",16,"我很美");
Person p3 = new Person("小利",16,"我很丑");
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
String js = new com.google.gson.Gson().toJson(list);
System.out.println(js);
List<Person> lists = new com.google.gson.Gson().fromJson(js,List.class);
System.out.println(lists.toString());
}
}
通过Gson().toJson(Objcet);
把指定对象转化为String对象.(Object -->Json)
通过Gson().fromJson(Object);
把String类型的JSON对象转化为原数据类型
输出结果:
2.通过阿里FastJson转化Json对象:
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.List;
public class FastJson {
public static void main(String[] args) {
Person p1 = new Person("小明",16,"我很帥");
Person p2 = new Person("小紅",16,"我很美");
Person p3 = new Person("小利",16,"我很丑");
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
String js = JSON.toJSONString(list);
System.out.println(js);
List<Person> list1 = JSON.parseObject(js,List.class);
List list2 = JSON.parseArray(js,String.class);
System.out.println(list1.toString());
System.out.println(list2.toString());
System.out.println(list1.getClass());
System.out.println(list2.getClass());
}
}
通过JSON().toJSONString(Objcet);
把指定对象转化为String对象.(Object -->Json)
通过JSON.parseObject(String,XXX.class);
把String类型的JSON对象转化为指定数据类型(XXX)