美文网首页
GSON使用记录

GSON使用记录

作者: King_Karl | 来源:发表于2019-07-30 11:35 被阅读0次

    需求

    gson是常用的框架

    分析

    1.如何解析数组

    [
      {
        "id": "1",
        "tag": "tag1",
        "tobe": "tobe1"
      },
      {
        "id": "2",
        "tag": "tag2",
        "tobe": "tobe2"
      }
    ]
    
    Gson gson = new Gson();
    Course[] courses = gson.fromJson(sg.toString(), Course[].class);
    

    2.带数据头的数组数据

    {
      "code":"1",
      "msg":"success",
      "data":[
        { "id": "1",
          "info": "1连",
          "parent_id":"0",
          "tobe": "tobe1"
        },
        { "id": "2",
          "info": "2连",
          "parent_id":"1",
          "tobe": "tobe1"
        },
        { "id": "3",
          "info": "3连",
          "parent_id":"2",
          "tobe": "tobe1"
        }
      ]
    }
    
    public class DataHead<T> {
    
        public int code;
    
        public String msg;
    
       @SerializedName(value = "datas",alternate = {"data","dataa"})
        public T[] datas;
    }
    
    Gson gson = new Gson();
    Type unitType = new TypeToken<DataHead<Unit>>(){}.getType();
    DataHead<Unit> head = gson.fromJson(str,unitType);
    return head.datas;
    
    

    3.jsonReader使用

    4.遇到空字符串时如果转换类型会报错的

    过程

    相关文章

      网友评论

          本文标题:GSON使用记录

          本文链接:https://www.haomeiwen.com/subject/ddvgrctx.html