Kotlin中使用Gson解析遇到的问题
Kotlin中使用Gson解析遇到的问题
data.json(json文件放在了assets里)
1 { 2 "success": true, 3 "value": [ 4 { 5 "id": 1000, 6 "name": "coco", 7 "age": 18 8 } 9 ] 10 }
用Java写,使用Gson解析:
1 new Thread(new Runnable() { 2 @Override 3 public void run() { 4 String json = FileUtils.getJson(TestActivity.this, "data.json"); 5 Type type = new TypeToken>>() { 6 }.getType(); 7 BaseModel > model = new Gson().fromJson(json, type); 8 System.out.println("@@@" + model.getValue().get(0).getName()); 9 } 10 }).start();
用Kotlin写,使用Gson解析:
1 Thread { 2 val json = FileUtils.getJson(this, "data.json") 3 val type: Type = object : TypeToken>>() {}.type 4 val model = Gson().fromJson >> (json, type) 5 println(model?.value?.get(0)?.name) 6 }.start()
遇到的问题:
1、用object,(对象表达式常用来作为匿名内部类的实现)。
2、Gson.fromJson
3、由于要从assets中取json数据,所以要在子线程中获取。
另附:
《Kotlin使用Gson总结》https://juejin.cn/post/6904455115885772807#comment