普通对象转换JSON
//创建JS对象
var obj = {"name":"张三","sex":"男","age":18};
//将JS对象转换成JSON格式字符串
var jsonStr = JSON.stringify(obj);
列表(集合)对象转换为JSON
function Person(name,sex,age) {
this.name = name;
this.sex = sex;
this.age = age;
}
var p1 = new Person("张三","男",18);
var p2 = new Person("李四","男",19);
var p3 = new Person("小丽","女",18);
var list = [];
list[0] = p1;
list[1] = p2;
list[2] = p3;
var json = JSON.stringify(list);
console.log(json);
JSON转换为js对象
JSON转换为普通对象
var jsonStr = '{"name":"张三","sex":"男","age":18}';
var obj = eval("("+jsonStr+")");
console.log(obj.name);
JSON转换为列表(集合)
var json = '[
{"name":"张三","sex":"男","age":18},
{"name":"李四","sex":"男","age":19},
{"name":"小丽","sex":"女","age":18}
]';
var list = eval("("+json+")");
console.log(list[0].name);
Java
三方包:
FASTJson
GSON
JackSon
注意: 常用GSON,需要导入GSON的jar包
对象转换为JSON
普通对象转换为JSON
Person person = new Person("张三", "男", 18);
Gson gson = new Gson();
String json = gson.toJson(person);
System.out.println(json);
//转换后数据: {"name":"张三","sex":"男","age":18}
集合对象转换为JSON
Person p01 = new Person("张三", "男", 18);
Person p02 = new Person("李四", "男", 19);
Person p03 = new Person("小丽", "女", 18);
ArrayList<Person> list = new ArrayList<>();
list.add(p01);
list.add(p02);
list.add(p03);
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(json);
/*
转换后数据: [{"name":"张三","sex":"男","age":18},{"name":"李四","sex":"男","age":19},{"name":"小丽","sex":"女","age":18}]
*/
字典对象转换为JSON
Person p01 = new Person("张三", "男", 18);
Person p02 = new Person("李四", "男", 19);
Person p03 = new Person("小丽", "女", 18);
HashMap<String, Person> map = new HashMap<>();
map.put("220101",p01);
map.put("220102",p02);
map.put("220103",p03);
Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);
/*
{"220102":{"name":"李四","sex":"男","age":19},"220101":{"name":"张三","sex":"男","age":18},"220103":{"name":"小丽","sex":"女","age":18}}
*/
JSON转换为对象
JSON字符串转换为普通对象
String json = "{'name':'张三','sex':'男','age':18}";
Person p = gson.fromJson(json, Person.class);
JSON字符串转换为集合
String json = "[{'name':'张三','sex':'男','age':18},
{'name':'李四','sex':'男','age':19},
{'name':'小丽','sex':'女','age':18}]";
Type type = new TypeToken<ArrayList<Person>>(){}.getType();
ArrayList<Person> ps = gson.fromJson(json, type);
System.out.println(ps.get(0).getName());
JSON字符串转换为字典
String json = "{
'220102':{'name':'李四','sex':'男','age':19},
'220101':{'name':'张三','sex':'男','age':18},
'220103':{'name':'小丽','sex':'女','age':18}
}";
Type type = new TypeToken<Map<String,Person>>(){}.getType();
Map<String,Person> m = gson.fromJson(json, type);
System.out.println(m.get("220101").getName());