关于json是什么,在这里就不做介绍,相信看这篇文章的同学都知道。
Gson--是一款Google公司的用来解析json数据格式的库
Fastjson--是一款阿里巴巴的用来解析json数据格式的库,据说目前最快。
首先介绍Gson的使用(下载前需要去下载,www.json.org都有链接,自己去找)
1、将一个JavaBen转换为json字符串
方便起见,把所有的类写在同一个文件里面
public class Main
{
public static void main(String[] args)
{
Person p=new Person(23,"gavin");
SchoolInfo school=new SchoolInfo("good","sh");
p.setInfo(school);
List<Friend> friends=new ArrayList();
Friend f1=new Friend("aviva1");
Friend f2=new Friend("aviva2");
Friend f3=new Friend("aviva3");
Friend f4=new Friend("aviva4");
friends.add(f1);
friends.add(f2);
friends.add(f3);
friends.add(f4);
p.setFriends(friends);
Gson gson=new Gson();
System.out.println(gson.toJson(p));
}
}
class Person
{
int age;
String name;
SchoolInfo info;
List<Friend> friends;
public Person(int age,String name)
{
this.age=age;
this.name=name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SchoolInfo getInfo() {
return info;
}
public void setInfo(SchoolInfo info) {
this.info = info;
}
public List<Friend> getFriends() {
return friends;
}
public void setFriends(List<Friend> friends) {
this.friends = friends;
}
}
class SchoolInfo
{
String name;
String addr;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public SchoolInfo(String name,String addr)
{
this.name=name;
this.addr=addr;
}
}
class Friend
{
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Friend(String name)
{
this.name=name;
}
}
运行结果:
{"age":23,"name":"gavin","info":{"name":"good","addr":"sh"},"friends":[{"name":"aviva1"},{"name":"aviva2"},{"name":"aviva3"},{"name":"aviva4"}]}
2、将上面得到的字符串转换成一个Persn
String txt=gson.toJson(p);
Person person=gson.fromJson(txt, Person.class);
System.out.println(person);
3、json字符串和List之间转换
编写一个Student 类
class Student
{
int age;
String name;
public Student(int age,String name)
{
this.age=age;
this.name=name;
}
}
Main方法
Student s1=new Student(1,"gavin");
Student s2=new Student(2,"aviva");
List<Student> stus=new ArrayList();
stus.add(s1);
stus.add(s2);
Gson gson=new Gson();
System.out.println(gson.toJson(stus));
结果
[{"age":1,"name":"gavin"},{"age":2,"name":"aviva"}]
将上述字符串转换为List
String t=gson.toJson(stus);
List<Student> list=gson.fromJson(t, new TypeToken<List<Student>>(){}.getType());
System.out.println(list);
3、实现Map和json字符串转换
HashMap<String ,String> map=new HashMap();
map.put("1", "gavin");
map.put("2", "aviva");
Gson gson=new Gson();
System.out.println(gson.toJson(map));
String t=gson.toJson(map);
HashMap<String,String> m=gson.fromJson(t, new TypeToken<HashMap<String,String>>(){}.getType());
由于时间有限,在此fastjsaon就不在做介绍,其用法和Gson基本相同..............