日期:2014-05-16 浏览次数:20406 次
package fastjson; import java.util.*; import com.alibaba.fastjson.JSON; class User{ private String name; private int age; public User(){ } public User(String name,int age){ this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } class Group{ private String id; private String name; private List<User> users = new ArrayList<User>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } } public class Main { public static void main(String[] args) { Group group = new Group(); group.setId("01"); group.setName("team gourp"); List<User> users = new ArrayList<User>(); users.add(new User("tomcat",12)); users.add(new User("jerry",12)); group.setUsers(users); //转成json字符串 String jsonString = JSON.toJSONString(group); System.out.println(jsonString); //将json字符串转成对象 Group g = JSON.parseObject(jsonString, Group.class); System.out.println(g.getUsers().get(0).getName()); } }
{"id":"01","name":"team gourp","users":[{"age":12,"name":"tomcat"},{"age":12,"name":"jerry"}]} tomcat
<html> <head> <script type="text/javascript"> var obj = eval("("+'{"id":"01","name":"team gourp","users":[{"age":12,"name":"tomcat"},{"age":12,"name":"jerry"}]}'+")"); alert(obj.id+","+obj.users[0].name+","+obj.users[1].name); </script> </head> </html>
01,tomcat,jerry
var json='{"name":"CJ","age":18}'; data =(new Function("","return "+json))();