• gson-2.2.api简单


    使用gson的tojson和fromjson实现对象和json的转换

    Gson gson = new Gson(); // Or use new GsonBuilder().create();
         MyType target = new MyType();
         String json = gson.toJson(target); // serializes target to Json
         MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

     Type listType = new TypeToken<List<String>>() {}.getType();
         List<String> target = new LinkedList<String>();
         target.add("blah");
         Gson gson = new Gson();
         String json = gson.toJson(target, listType);
         List<String> target2 = gson.fromJson(json, listType);

     使用GsonBuilder创建gson对象
          Gson gson = new GsonBuilder()
             .registerTypeAdapter(Id.class, new IdTypeAdapter())
             .enableComplexMapKeySerialization()
             .serializeNulls()
             .setDateFormat(DateFormat.LONG)
             .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
             .setPrettyPrinting()
             .setVersion(1.0)
             .create();
     
               Gson gson = new GsonBuilder()
           .register(Point.class, new MyPointTypeAdapter())
           .enableComplexMapKeySerialization()
           .create();

    map对象转换成json对象

      Gson gson = new GsonBuilder()
           .register(Point.class, new MyPointTypeAdapter())
           .enableComplexMapKeySerialization()
           .create();

       Map<Point, String> original = new LinkedHashMap<Point, String>();
       original.put(new Point(5, 6), "a");
       original.put(new Point(8, 8), "b");
       System.out.println(gson.toJson(original, type));
     

        The above code prints this JSON object:

      {
         "(5,6)": "a",
         "(8,8)": "b"
       }


     map对象转化成jsonArray对象:

    Gson gson = new GsonBuilder()
           .enableComplexMapKeySerialization()
           .create();
    
       Map<Point, String> original = new LinkedHashMap<Point, String>();
       original.put(new Point(5, 6), "a");
       original.put(new Point(8, 8), "b");
       System.out.println(gson.toJson(original, type));
     
    
     The JSON output would look as follows:
       [
         [
           {
             "x": 5,
             "y": 6
           },
           "a"
         ],
         [
           {
             "x": 8,
             "y": 8
           },
           "b"
         ]
       ]


    JsonParser

    parse方法将json类型的字符串,或者reader对象或者JsonReader对象解析成为jsonElement对象

  • 相关阅读:
    ubuntu apt-get工作原理
    关联式容器(associative containers)
    qsort()与besearch()
    D&F学数据结构系列——插入排序
    D&F学数据结构系列——二叉堆
    Windows 系统环境变量的配置
    Python 的版本选择与安装细节
    计算机基础知识总结
    PEP 8 -- Python代码格式规则
    day57 Django补充内容(中间件其他方法、jQuery操作cookie、csrf详解和form组件简单使用)
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5513238.html
Copyright © 2020-2023  润新知