[英]How to convert JSONArray to List with Gson?
In my Android project I'm trying to convert a received JSONArray to a List. 在我的Android项目中,我正在尝试将收到的JSONArray转换为List。 With the help of this SO answer I got a bit further. 在这个SO答案的帮助下,我得到了更多。 I now have the following code: 我现在有以下代码:
Gson gson = new Gson();
JSONArray jsonArray = NetworkUtilities.getData("mymodeldata");
Type listType = new TypeToken<List<MyModel>>(){}.getType();
List<MyModel> myModelList = gson.fromJson(jsonArray, listType);
Unfortunately it complaints at the last line that the method fromJson(String, Type) in the type Gson is not applicable for the arguments (JSONArray, Type). 不幸的是,它在最后一行抱怨Gson类型中的fromJson(String,Type)方法不适用于参数(JSONArray,Type)。 I don't really know how to solve this. 我真的不知道如何解决这个问题。
Does anybody know how I can solve this? 有谁知道我怎么解决这个问题?
If you see the answer there, you can notice that the first parameter in the fromJson()
method was a String
(the json object). 如果你在那里看到答案,你会注意到fromJson()
方法中的第一个参数是一个String
(json对象)。 Try to use the toString()
on the JsonArray like this:- 尝试在JsonArray上使用toString()
,如下所示: -
List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.