1. JSON description.
JSON (JavaScript Object Notation) is a lightweight data interchange format. It is based on a subset of ECMAScript. JSON is in a completely language-independent text format, but also uses conventions similar to the C language family (including C, C++, C#, Java, JavaScript, Perl, Python, etc.). These properties make JSON an ideal data interchange language. It is easy for humans to read and write, but also easy for machines to parse and generate (generally used to increase network transmission rates).
2. Grammar rules.
1. JSON is a collection of 'name/value' pairs, in the format of 'name/value', for example, "key1":value1.
2. The value of JSON can be a string enclosed in double quotes, a number, true, false, null, an object or an array.
3.JSON has two structures, one is an object and the other is an array.
(1). The object (object) is an unordered collection of "'name/value' pairs". An object begins with "{" (left bracket) and ends with "}" (right bracket). Each 'name' is followed by a ':' (colon); 'name/value' pairs are separated by a ',' (comma). It is enclosed by {}, for example, {"key1":value1,"key2":value2,"key3":value3,...}.
(2). Array (array) is an ordered collection of values. An array starts with "[" (left bracket) and ends with "]" (right bracket). Values are separated by "," (comma) and are enclosed in []. For example, the format is [{"key1":value1,"key2":value2,"key3":value3},{"key1":value1,"key2":value2,"key3":value3}...].
3. Function
Fourth, the use of JSON in web projects
1. jQuery's ajax method passes json to the background
(1). Example 1:
$.ajax({
type:"POST",
url:"sysAllTableAction_saveTable.do",
data:{jsonStr: JSON.stringify(array_json)},
dataType:"text json",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
cache:false,
success:function(msg){
alert(msg);
},
error:function(){
alert("error");
}
});
(2). Example 2:
var form_vals = $('#form1').serializeArray();
$.post("PmpAction_toUpdate.do",form_vals,function(data){
if(data=="success"){
alert("修改成功!");
window.location.href="PmpAction_List.do";
}
});
2. Conversion of JSON data
(1). Serialize the content of the form and convert it to JSON
var t="{'firstName': 'cyra', 'lastName': 'richardson', 'address': {'streetAddress': '1 Microsoft way', 'city': 'Redmond'},
'phoneNumbers': ['425-777-7777','206-777-7777']}";
var jsonobj=eval('('+t+')');
alert(jsonobj.firstName);
alert(jsonobj.lastName);
3. Parsing of JSON data in the page.
5. JSON parsing.
1. Create a new test project.
entity class
public class Person {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
Parse using GSON and JackJson respectively.
2. GSON. GSON is a Java API developed by Google to convert Java objects and Json objects.
2.1. First download the jar imported into GSON.
(1). You can go to the github link , download the source code of GSON, compile it yourself, and generate a jar;
(2). You can also directly download the jar package, GSONjar package download link.
(3). gson-2.6.6.jar download link.
2.2. Generate objects.
public static void main(String[] args) {
Gson gson=new Gson();
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
String str=gson.toJson(person);
System.out.println(str);
}
2.3. Output results.
{"id":1,"name":"zhangsan","age":30}
2.4. Generate an array.
public static void main(String[] args) {
List<Person> list=new ArrayList<Person>();
Gson gson=new Gson();
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
list.add(person);
Person person1=new Person();
person1.setId(2);
person1.setName("lisi");
person1.setAge(20);
list.add(person1);
String str=gson.toJson(list);
System.out.println(str);
}
2.5. Output results.
[{"id":1,"name":"zhangsan","age":30},{"id":2,"name":"lisi","age":20}]
2.6.json parsing object.
public static void main(String[] args) {
String str="{\"id\":1,\"name\":\"zhangsan\",\"age\":30}";
Gson gson=new Gson();
Person person=gson.fromJson(str, Person.class);
System.out.println(person.toString());
}
2.7. Output results.
Person [id=1, name=zhangsan, age=30]
2.8.json parses the array.
public static void main(String[] args) {
String str = "[{\"id\":1,\"name\":\"zhangsan\",\"age\":30},{\"id\":2,\"name\":\"lisi\",\"age\":20}]";
Gson gson = new Gson();
Type type = new TypeToken<List<Person>>() {
}.getType();
List<Person> list = gson.fromJson(str, type);
for (Person person : list) {
System.out.println(person.toString());
}
}
2.9. Output results.
Person [id=1, name=zhangsan, age=30]
Person [id=2, name=lisi, age=20]
3.JackJson。
The Jackson framework is a set of data processing tools based on the Java platform, known as "the best Java Json parser".
The Jackson framework includes three core libraries: streaming, databind, and annotations.
3.1 Library download address .
Jackson https://github.com/FasterXML/jackson-core/wiki
Databind https://github.com/FasterXML/jackson-databind
Annotations https://github.com/FasterXML/jackson-annotations/wiki
Jackson doc https://github.com/FasterXML/jackson-docs
3.2. Generate objects.
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
ObjectMapper objectMapper = new ObjectMapper();
try {
String json=objectMapper.writeValueAsString(person);
System.out.println(json);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();}
3.3. 结果。
{"id":1,"name":"zhangsan","age":30}
3.4. Generating arrays
List<Person> list=new ArrayList<Person>();
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
list.add(person);
Person person1=new Person();
person1.setId(2);
person1.setName("lisi");
person1.setAge(20);
list.add(person1);
Person person2=new Person();
person2.setId(3);
person2.setName("wangwu");
person2.setAge(30);
list.add(person1);
ObjectMapper objectMapper = new ObjectMapper();
try {
String json=objectMapper.writeValueAsString(list);
System.out.println(json);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
3.5. Results.
[{"id":1,"name":"zhangsan","age":30},{"id":2,"name":"lisi","age":20},{"id":2,"name":"lisi","age":20}]
3.6.json parsing object.
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
ObjectMapper objectMapper = new ObjectMapper();
try {
String json=objectMapper.writeValueAsString(person);
System.out.println(json);
Person info=objectMapper.readValue(json, Person.class);
System.out.println(info.toString());
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
3.7 Results.
{"id":1,"name":"zhangsan","age":30}
Person [id=1, name=zhangsan, age=30]
3.8.json parsing arrays.
List<Person> list=new ArrayList<Person>();
Person person=new Person();
person.setId(1);
person.setName("zhangsan");
person.setAge(30);
list.add(person);
Person person1=new Person();
person1.setId(2);
person1.setName("lisi");
person1.setAge(20);
list.add(person1);
Person person2=new Person();
person2.setId(3);
person2.setName("wangwu");
person2.setAge(30);
list.add(person1);
ObjectMapper objectMapper = new ObjectMapper();
try {
String json=objectMapper.writeValueAsString(list);
System.out.println(json);
Person[] persons=objectMapper.readValue(json, Person[].class);
for (Person info:persons) {
System.out.println(info.toString());
}
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.9 Results.
[{"id":1,"name":"zhangsan","age":30},{"id":2,"name":"lisi","age":20},{"id":2,"name":"lisi","age":20}]
Person [id=1, name=zhangsan, age=30]
Person [id=2, name=lisi, age=20]
Person [id=2, name=lisi, age=20]