Json前后端应用场景广泛:
1、前端获取后端的数据可以为json类型,通过json解析展示到页面;
2、后端:
(1)给前端提供数据;
(2)提供远程调用接口数据;
(3)json解析,重新赋值,做国际化应用等等。
依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
对象
package com.os.china.entity;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private Integer age;
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Person() {
super();
}
public Person(String id, String name, Integer age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
JsonUtil
作用:初始化数据
package com.os.china.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.os.china.entity.Person;
public class JsonUtil {
public static JSONObject json() {
JSONObject json = new JSONObject();
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Person p1 = new Person("1", "哈哈一", 18);
Person p2 = new Person("2", "哈哈二", 20);
List<Person> object = new ArrayList<Person>();
object.add(p1);
object.add(p2);
Map<String, Object> map = new HashMap<String, Object>();
map.put("一", 1);
map.put("二", 2);
map.put("p1", p1);
map.put("p2", p2);
// 添加字符串集合
json.put("list", list);
// 添加含有对象的集合
json.put("object", object);
// 添加map集合
json.put("map", map);
return json;
}
}
测试代码
import com.os.china.util.JsonUtil;
/**
*json解析
*/
public class Test {
public static void main(String[] args) {
JSONObject json = JsonUtil.json();
//解析集合里每个值
JSONArray array = json.getJSONArray("list");
for (int i = 0; i < array.size(); i++) {
String object =(String) array.get(i);
System.err.println(object);
}
//解析含有对象的集合
JSONArray newArray = json.getJSONArray("object");
for (int i = 0; i < newArray.size(); i++) {
JSONObject jsonObject = newArray.getJSONObject(i);
Integer age = (Integer)jsonObject.get("age");
System.err.println(age);
String id = (String)jsonObject.get("id");
System.err.println(id);
String name = (String)jsonObject.get("name");
System.err.println(name);
}
//解析map集合(含对象)
Map<String, Object> object =(Map<String, Object>) json.get("map");
if (object!=null&&!object.isEmpty()) {
Set<String> key = object.keySet();
for (String s : key) {
System.err.println(object.get(s));
}
}
}
}
执行结果:
a
b
18
1
哈哈一
20
2
哈哈二
1
Person [id=1, name=哈哈一, age=18]
Person [id=2, name=哈哈二, age=20]
2