fastjson的使用

这里介绍fastjson用于生成和解析JSON数据的简单示例

publicclassUser{

privateLongid;

privateStringname;

publicLonggetId(){returnid;}

publicvoidsetId(Longid){this.id=id;}

publicStringgetName(){returnname;}

publicvoidsetName(Stringname){this.name=name;}

}

publicclassGroup{

privateLongid;

privateStringname;

privateList<User>users=newArrayList<User>();

publicLonggetId(){returnid;}

publicvoidsetId(Longid){this.id=id;}

publicStringgetName(){returnname;}

publicvoidsetName(Stringname){this.name=name;}

publicList<User>getUsers(){returnusers;}

publicvoidsetUsers(List<User>users){this.users=users;}

}

importcom.alibaba.fastjson.JSON;

Groupgroup=newGroup();

group.setId(0L);

group.setName("admin");

UserguestUser=newUser();

guestUser.setId(2L);

guestUser.setName("guest");

UserrootUser=newUser();

rootUser.setId(3L);

rootUser.setName("root");

group.getUsers().add(guestUser);

group.getUsers().add(rootUser);

StringjsonString=JSON.toJSONString(group);

System.out.println(jsonString);

{

"name":"admin",

"id":0,"users":[

{"name":"guest","id":2},

{"name":"root","id":3}

]

}

Groupgroup2=JSON.parseObject(jsonString,Group.class);

相关推荐