基于Gson的接口数据转换

2022-10-20  本文已影响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) {
}

上一篇 下一篇

猜你喜欢

热点阅读