您的位置:首页 > Web前端 > JavaScript

JSON学习总结

2015-04-11 23:15 176 查看
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成(网络传输速度)。

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。

1、对象:对象在js中表示为“{}”括起来的内容,数据结构为 {key:value,key:value,…}的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是 数字、字符串、数组、对象几种。

2、数组:数组在js中是中括号“[]”括起来的内容,数据结构为 [“java”,”javascript”,”vb”,…],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种。

经过对象、数组2种结构就可以组合成复杂的数据结构了。

下面通过案例学习JSON:

1.json对象与java对象的转换

/**
 * 把一个对象转换成jsonObject对象
 */
@Test
    public void test(){
        //创建一个对象
        Student stu = new Student("Leo");
        //转换成json数据
        JSONObject json = JSONObject.fromObject(stu);
        //{"name":"Leo"}
        System.out.println(json);
    }


输出结果:{“name”:”Leo”}

/**
 * 把一个对象转换成jsonObject对象
 */
@Test
    public void test2(){
        //创建一个对象
        List<Student> stus = new ArrayList<Student>();
        stus.add(new Student("Leo1"));
        stus.add(new Student("Leo2"));
        stus.add(new Student("Leo3"));
        stus.add(new Student("Leo4"));

        Teacher teacher = new Teacher();

        teacher.setAge(18);
        teacher.setBirth(new Date(1998, 1, 12));
        teacher.setName("八戒");
        teacher.setSex("男");

        teacher.setStudents(stus);
        //转换成json数据
        JSONObject json = JSONObject.fromObject(teacher);
        System.out.println(json);
    }


输出结果:


/**
 * 把一个jsonobject对象转换成一个 Teacher对象
 */
    @Test
    public void test3(){
        //json数据
        String json ="{'age':18,'birth':{'date':12,'day':6,'hours':0,'minutes':0,'month':1,'seconds':0,'time':60845443200000,'timezoneOffset':-480,'year':1998},'name':'八戒','sex':'男','students':[{'name':'Leo1'},{'name':'Leo2'},{'name':'Leo3'},{'name':'Leo4'}]}";

        //转换成json数据
        JSONObject json2 = JSONObject.fromObject(json);

        //转换成java对象
        Teacher ttt=(Teacher) JSONObject.toBean(json2, Teacher.class);

        System.out.println(ttt.toString());
    }


输出结果:

Teacher [name=八戒, sex=男, age=18, birth=Sat Feb 12 00:00:00 CST 3898, students=[net.sf.ezmorph.bean.MorphDynaBean@75bd9247[

{name=Leo1}

], net.sf.ezmorph.bean.MorphDynaBean@7d417077[

{name=Leo2}

], net.sf.ezmorph.bean.MorphDynaBean@7dc36524[

{name=Leo3}

], net.sf.ezmorph.bean.MorphDynaBean@35bbe5e8[

{name=Leo4}

]]]

/**
* 把一个集合转换成JsonArray数组
 */
    @Test
    public void test4(){
        List<Student> stus = new ArrayList<Student>();
        stus.add(new Student("Leo1"));
        stus.add(new Student("Leo2"));
        stus.add(new Student("Leo3"));
        stus.add(new Student("Leo4"));

        //转换成json
        JSONArray array = JSONArray.fromObject(stus);
        //
        System.out.println(array);
    }


输出结果:

[{“name”:”Leo1”},{“name”:”Leo2”},{“name”:”Leo3”},{“name”:”Leo4”}]

/**
     * 把一个jsonarray数组转换成 集合对象
     */
    @Test
    public void test5(){
        String json="[{'name':'Leo1'},{'name':'Leo2'},{'name':'Leo3'},{'name':'Leo4'}]";
        //转换成json
        JSONArray array = JSONArray.fromObject(json);

        List<Student> list = JSONArray.toList(array);
        System.out.println(list);
    }


输出结果:

[net.sf.ezmorph.bean.MorphDynaBean@18ef96[

{name=Leo1}

], net.sf.ezmorph.bean.MorphDynaBean@6956de9[

{name=Leo2}

], net.sf.ezmorph.bean.MorphDynaBean@769c9116[

{name=Leo3}

], net.sf.ezmorph.bean.MorphDynaBean@6aceb1a5[

{name=Leo4}

]]

/**
 * 注:
 * 对象与json的转换 需要引入json的类库文件
 * \lib\commons-beanutils-1.7.0.jar
 * \lib\commons-collections-3.2.jar
 * \lib\commons-lang-2.3.jar
 * \lib\commons-logging-1.0.4.jar
 * \lib\ezmorph-1.0.6.jar
 * \lib\json-lib-2.4-jdk15.jar 需要使用它
 */


2.servlet响应json数据的操作实现

package js_01.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import js_01.domain.Student;
import js_01.domain.Teacher;
import net.sf.json.JSONObject;

public class JsonServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        //创建一个对象
        List<Student> stus = new ArrayList<Student>();
        stus.add(new Student("Leo1"));
        stus.add(new Student("Leo2"));
        stus.add(new Student("Leo3"));
        stus.add(new Student("Leo4"));

        Teacher teacher = new Teacher();

        teacher.setAge(18);
        teacher.setBirth(new Date(1998, 1, 12));
        teacher.setName("八戒");
        teacher.setSex("男");

        teacher.setStudents(stus);
        //转换成json数据
        JSONObject json = JSONObject.fromObject(teacher);

        //写出去  响应的类型是json数据格式
        response.getOutputStream().write(json.toString().getBytes());
        response.setContentType("application/json");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doGet(request, response);

    }

}


响应结果:



3.javascript原始对象的写法

<script type="text/javascript">
    //用户对象
    var u={name:"leoleo",age:20,sex:"男"};

    alert(u.name);
    alert(u.age);
    alert(u.sex);

    //复杂对象
    var cls={
         name:"计算机科学与技术xxx班",
         users:[
             {name:"Leo",age:21,sex:"male"},
             {name:"Leo2",age:21,sex:"male"},
             {name:"Leo3",age:21,sex:"male"},
             {name:"Leo4",age:21,sex:"male"},
             {name:"Leo5",age:21,sex:"male"}
         ],
         teacher:{name:"leoleohan"}
    };

    //遍历班级
    document.write("班级的名称"+cls.name+"<br/>");
    document.write("班级的授课教师:"+cls.teacher.name+"<br/>");

    //遍历班级的成员
    for(uu in cls.users){
        document.write(cls.users[uu].name+"-"+cls.users[uu].age+"-"+cls.users[uu].sex+"-"+cls.users[uu].fav+"<br/>");
    }

     document.write("-----------------------------<br/>");
    //获取所有的学生信息
    var users = cls.users;
    //遍历
    for(var i=0;i<users.length;i++){
          //取得指定的学生对象
          var ru=users[i];
          //输出学生信息
          document.write(ru.name+"-"+ru.age+"-"+ru.sex+"-"+ru.fav+"<br/>");
    }
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: