zoukankan      html  css  js  c++  java
  • 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对象

  • 相关阅读:
    CF991D Bishwock
    CF1010D Mars rover
    NOIP 2011 计算系数
    SDOI 2008 仪仗队
    浅谈欧拉函数
    CF1249F Maximum Weight Subset
    NOIP 2011 铺地毯
    CF707D Persistent Bookcase
    C++ STL bitset 容器详解
    CF798D Mike and distribution
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5513238.html
Copyright © 2011-2022 走看看