public void objectOrArray() {
String data = "{\"person\":[{\"age\":\"1\"},{\"age\":\"22\"},{\"age\":\"333\"}]}";
Object parse = JSONObject.parse(data);
//方法一
if (parse instanceof JSONArray) {
System.out.println("data是一个数组");
}
if (parse instanceof JSONObject) {
System.out.println("data是一个对象");
}
//方法二
try {
Map map = (Map)parse;
} catch (Exception e) {
System.out.println("该数据不属于对象");
}
try {
List list = (List)parse;
} catch (Exception e) {
System.out.println("该数据不属于数组");
}
}
public void test() {
List<Student> students = new ArrayList<>();
Student student1 = new Student("alex","12");
Student student2 = new Student("afra","13");
Student student3 = new Student("mary", "34");
students.add(student1);
students.add(student2);
students.add(student3);
List<Life> list = new ArrayList<>();
Life life1 = new Life("ic1", students);
Life life2 = new Life("ic2", students);
Life life3 = new Life("ic3", students);
list.add(life1);
list.add(life2);
list.add(life3);
Bao bao = new Bao(list);
String s = JSON.toJSONString(bao);
Object o = JSON.toJSON(bao);
System.out.println(s);
System.out.println(o);
}
class Bao implements Serializable {
public List<Life> list;
public Bao(List<Life> list) {
this.list = list;
}
}
class Life implements Serializable {
public String ic;
public List<Student> students;
public Life(String ic, List<Student> students) {
this.ic = ic;
this.students = students;
}
}
class Student implements Serializable {
public String name;
public String age;
public Student(String name, String age) {
this.name = name;
this.age = age;
}
}
打印结果
{
"list": [
{
"ic": "ic1",
"students": [
{
"age": "12",
"name": "alex"
},
{
"age": "13",
"name": "afra"
},
{
"age": "34",
"name": "mary"
}
]
},
{
"ic": "ic2",
"students": [
{
"$ref": "$.list[0].students[0]"
},
{
"$ref": "$.list[0].students[1]"
},
{
"$ref": "$.list[0].students[2]"
}
]
},
{
"ic": "ic3",
"students": [
{
"$ref": "$.list[0].students[0]"
},
{
"$ref": "$.list[0].students[1]"
},
{
"$ref": "$.list[0].students[2]"
}
]
}
]
}
{
"list": [
{
"students": [
{
"name": "alex",
"age": "12"
},
{
"name": "afra",
"age": "13"
},
{
"name": "mary",
"age": "34"
}
],
"ic": "ic1"
},
{
"students": [
{
"name": "alex",
"age": "12"
},
{
"name": "afra",
"age": "13"
},
{
"name": "mary",
"age": "34"
}
],
"ic": "ic2"
},
{
"students": [
{
"name": "alex",
"age": "12"
},
{
"name": "afra",
"age": "13"
},
{
"name": "mary",
"age": "34"
}
],
"ic": "ic3"
}
]
}
仔细观察也能发现两个方法打印出来的还是有区别的