zoukankan      html  css  js  c++  java
  • JSON

    JSON:
    什么是json?
    json是用花括号括起来的键值对结构。键和值之间用分号(:)分开,键值对之间用逗号分开(,)分开。
    json的键必须是String 类型,即必须用双引号引起来,而值就不一定用双引号引起来。
    {"name":"zhangsan"}
    json在JS中的使用:
    json值的类型:
    json值的类型可以是
    数字{"password":123}
    数组 {"arr":[1,2,3]}数组用中括号([])括起来
    对象 {"date":new Date()}
    字符串{"name":"zhangsan"}
    布尔值{"gen":true}
    null {"age":null}
    json 的使用:
      用变量名+“.”+键的方式使用json中的值。
      var json={"name":"zhangsan"};
      alert(json.name);
    json Object和String的转换
      var json={"name":"zs"};
      var jsonStr=JSON.stringfy(json);//这样jsonStr 就是String类型的变量。
      var jsonObj=JSON.parse(josnStr);//这样jsonObj就是Object类型的变量。
      这里要说明一下json的类型就是Object类型。


    在servlet中的json:
    GSON工具类:
    需要引入两个包:commons-fileupload-1.3.1.jar
    commons-io-2.4.jar
    将普通对象转为json字符串。
    Student为提前创建的一个类
    Student stu=new Student("yr", "99");
    Gson gson=new Gson();
    String json = gson.toJson(stu);
    System.out.println(json);
    输出为{"name":"yr","score":"99"}

    将map转换成json对象
    Gson gson=new Gson();
    Map<String,String> map=new HashMap();
    map.put("name", "yr");
    map.put("age", "23");
    String json = gson.toJson(map);
    System.out.println(json);
    输出为{"name":"yr","age":"23"}
    将List转换为json字符串
    Gson gson=new Gson();
    List<String>list=new ArrayList<>();
    list.add("刘德华");
    list.add("周润发");
    String json = gson.toJson(list);
    System.out.println(json);
    输出为 ["刘德华","周润发"]


    将json转为对象
    Student stu=new Student("yr", "99");
    Gson gson=new Gson();
    String json = gson.toJson(stu);
    Student fromJson = gson.fromJson(json, Student.class);
    System.out.println(fromJson);
    输出为Student [name=yr, score=99]
    将json转换为map对象
    Gson gson=new Gson();
    Map<String,String> map=new HashMap();
    map.put("name", "yr");
    map.put("age", "23");
    String json = gson.toJson(map);

    Map<String, String> fromJson = gson.fromJson(json, Map.class));
    System.out.println(fromJson);
    输出为 {name=yr, age=23}

  • 相关阅读:
    ajax入门之建立XHR对象 (1)
    JavaScript中的函数有什么特点? 应该怎样优化?
    什么是JavaScript中的面向对象? 与其他编程语言的面向对象有什么区别? 什么是原型?
    Web页面加载,如何分析页面性能?如何进行优化?
    一个页面从输入 URL 到页面加载完的过程中都发生了什么事情?
    关于清除浮动与闭合浮动
    如何更加安全快速的使用富文本编辑器
    用Python实现一个爬取XX大学电费通知的小脚本
    在Sublime Text3上面更加方便愉快的写php
    如何搭建一个WAMP环境
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7399545.html
Copyright © 2011-2022 走看看