美文网首页
基于Gson的接口数据转换

基于Gson的接口数据转换

作者: 大浪捉鱼 | 来源:发表于2022-10-20 17:24 被阅读0次

接口返回json格式的数据,然后将string转成自定义的model或map或JSONObject

1、string转自定义model

假设SceneModel是自定义的数据结构

SceneModel scene = new Gson().fromJson(result, SceneModel.class);

如果是列表

List<SceneModel> sceneList = new Gson().fromJson(result,new TypeToken<List<SceneModel>>(){}.getType());

2、string转map

String result = "{ "status":200, "msg":"xxx"}";
Type type = new TypeToken<Map<String, Object>>(){}.getType();
Map<String, String> map = new Gson().fromJson(result, type);

3、string转JSONObject

try {
     JSONObject obj = new JSONObject(result);
     int status = obj.getInt("status");
      if (status == 200) {
           Log.i(TAG,"场景执行成功");
      }
                
} catch (JSONException e) {
}

相关文章

网友评论

      本文标题:基于Gson的接口数据转换

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