About JSON

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

1 JSON format verification
After getting JSON data, many people have no way to judge whether the format of JSON data is correct or not, and whether there are few or more symbols and the program cannot be parsed. This function can just help everyone to complete the verification of JSON format.
2 JSON view
Presumably many programmers will encounter that when looking for a node, they will find that if they directly face rows of data, they can't start. Even if they know where they are, they still have to search down node by node. Start looking for trouble.
With this function, all JSON data will be transformed into a view format, and it is clear at a glance, how many arrays are under what objects, and how many objects are under an array.
This function is very useful. Not only the view function but also the formatting, compression, escaping, and verification functions. Anyway very powerful.
3 Compression escape
When programmers write JSON statement test cases, they often write a JSON string directly for testing for convenience, but they fall into the endless trouble of escaping double quotes. This feature set compression and escaping in one, allowing you to write test cases like a duck to water.
4 JSON Online Editor
If your current computer doesn't happen to have an editor that you are familiar with, if you want to modify the data for a certain node of the JSON data obtained, this function can meet your needs.
5 Send JSON data online
We all know that JSON is mostly used in the development of web projects. If you want to test whether an interface can accurately accept JSON data, then you have to write a page to send JSON strings and do this repeatedly. With the emergence of this function, you can get rid of writing test pages, because this function can send the specified JSON data to the specified url, which is convenient.
6 JSON coloring
When many people write a document, they always hope that the document can be seen at a glance, but it doesn't matter if you are facing JSON data with black characters on a white background  .  It will be colored, and the data structure will be clear at a glance.
7 JSON-XML conversion
As the name suggests, converts JSON-formatted data into XML  [3]  Format, or data in XML format is converted into JSON format, all is not a problem.
8 JSON-VIEW
JSON viewing utility, which can format and view JSON data during the development process (in the Windows platform).
9 It is a data exchange format like xml

 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] 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613525&siteId=291194637