标签:
一、简介
2)存储和交换文本信息的语法。类似 XML
3)比 XML 更小、更快,更易解析
4)独立于语言
2、语法
1)花括号保存对象,方括号保存数组,数据在名称/值对中,数据由逗号分隔
例如:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
2)JSON 值可以是:
[{ "firstName":"John" , "lastName":"Doe" },{ "firstName":"Anna" , "lastName":"Smith" },{ "firstName":"Peter" , "lastName":"Jones" }]
-------------------------------------分割线---------------------------------------------------
下面举几个具体的列子理解下上面写的内容
1、JSONObject
定义一个JavaBean
public class Student { private String name; private int Grade; private List<String> teachers; public Student() { } public Student(String name, int grade, List<String> teachers) { super(); this.name = name; Grade = grade; this.teachers = teachers; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return Grade; } public void setGrade(int grade) { Grade = grade; } public List<String> getTeachers() { return teachers; } public void setTeachers(List<String> teachers) { this.teachers = teachers; } }
主方法:
public class TestJson { public static void main(String[] args) { List<String> teacherList = new ArrayList<String>(); teacherList.add("math"); teacherList.add("english"); Student stu = new Student("yaohuix", 2, teacherList); JSONObject jsonObject = JSONObject.fromObject(stu); // Bean转JSONObject或JSON字符串(只要toString()) System.out.println(jsonObject);// 输出:{"grade":15,"name":"yaohuix","teachers":["math","english"]} // JSONObject或JSON字符串(只要toString())转Bean Student otherStu = (Student) JSONObject.toBean(jsonObject, Student.class); System.out.println(otherStu.getName());// 输出:yaohuix System.out.println(otherStu.getGrade());// 输出:2 System.out.println(otherStu.getTeachers());// 输出:[math, english] } }
标签:
原文地址:http://www.cnblogs.com/activity/p/4875053.html