JSON應知應會

JSON簡介

簡介:
JSON(JavaScriptObject Notation)、輕量級數據交換格式、很是適合於服務器與 JavaScript 的交互。javascript

JSON兩種格式:

一、對象
對象是一個無序的「‘名稱/值’對」集合。一個對象以「{」(左括號)開始,「}」(右括號)結束。每一個「名稱」後跟一個「:」(冒號);「‘名稱/值’ 對」之間使用「,」(逗號)分隔。java

var person = { "name":"huochai", "age":29, "school":{ "name":"diankeyuan", "location":"beijing" }};

二、數組
數組是值(value)的有序集合。一個數組以「[」(左中括號)開始,「]」(右中括號)結束。值之間使用「,」(逗號)分隔。json

var students =  
              [  
                     {"sno":"001","name":"jack","age":130},  
                     {"sno":"002","name":"tame","age":120},  
                     {"sno":"003","name":"cule","age":110},  
              ];

一些JSON實例數組

var person = { "name":"huochai", "age":29, "school":{ "name":"diankeyuan", "location":"beijing" }};
        var strJson = '{ "name":"huochai", "age":29, "school":{ "name":"diankeyuan", "location":"beijing" }}';
        var aa = 'abc';
        var bb = ['baidu','taobao'];
        var cc = {'persons': ['zhangsan','lisi']};
        var students =
                [
                    {"sno":"001","name":"jack","age":130},
                    {"sno":"002","name":"tame","age":120},
                    {"sno":"003","name":"cule","age":110},
                ];

        var personOther = JSON.parse(strJson);

        alert(personOther.age);

JSON對象

  JSON之因此流行,是由於能夠把JSON數據結構解析爲有用的javascript對象服務器

  ECMAScript5對解析JSON的行爲進行了規範,定義了全局對象JSON數據結構

  JSON對象有兩個方法:stringify()和parse()。這兩個方法分別用於把JavaScript對象序列化爲JSON字符串和把JSON字符串解析爲原生JavaScript值code

stringify()

var strPerson = JSON.stringify(person);
alert(strPerson);
var strStudents = JSON.stringify(students);
alert(strStudents);

parse()

  JSON.parse方法用於將JSON字符串轉化成對象對象

var strPerson = JSON.stringify(person);
var personObj = JSON.parse(strPerson);
var strStudents = JSON.stringify(students);
var studentsObj = JSON.parse(strStudents);

對應的java表示:ip

public class Person {
    public String name;
    public int    age;
    public School school;
}
public class School {
    public String name;
    public String location;
}

利用fastjson將java對象轉換成JSON字符串字符串

Person person = new Person();
        person.name = "huochai";
        person.age = 29;
        person.school = new School();
        person.school.name = "diankeyuan";
        person.school.location = "beijing";


        String strJson = JSON.toJSONString(person);
        System.out.println(strJson);

        Person person2 = new Person();
        person2.name = "huochai2";
        person2.age = 292;
        person2.school = new School();
        person2.school.name = "diankeyuan2";
        person2.school.location = "beijing2";

        List<Person> lst = new ArrayList<Person>();
        lst.add(person);
        lst.add(person2);


        String strJson2 = JSON.toJSONString(lst);
        System.out.println(strJson2);
相關文章
相關標籤/搜索