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}

  • 相关阅读:
    算法提高 身份证号码升级
    枚举排列
    排列数
    算法训练 K好数
    算法训练 前缀表达式
    算法训练 区间k大数查询
    最大最小公倍数
    Anagrams问题
    Uiautomator 2.0
    Uiautomator 2.0
  • 原文地址:https://www.cnblogs.com/xuesheng/p/7399545.html
Copyright © 2011-2022 走看看