Java 如何使用 Gson 将 JSONArray 转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19133944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert JSONArray to List with Gson?
提问by kramer65
In my Android project I'm trying to convert a received JSONArray to a List. With the help of this SO answerI got a bit further. I now have the following code:
在我的 Android 项目中,我试图将接收到的 JSONArray 转换为列表。在这个 SO 答案的帮助下,我更进一步。我现在有以下代码:
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). I don't really know how to solve this.
不幸的是,它在最后一行抱怨 Gson 类型中的 fromJson(String, Type) 方法不适用于参数 (JSONArray, Type)。我真的不知道如何解决这个问题。
Does anybody know how I can solve this?
有谁知道我该如何解决这个问题?
采纳答案by SudoRahul
If you see the answer there, you can notice that the first parameter in the fromJson()
method was a String
(the json object). Try to use the toString()
on the JsonArray like this:-
如果您在那里看到答案,您会注意到该fromJson()
方法中的第一个参数是 a String
(json 对象)。尝试toString()
像这样在 JsonArray 上使用:-
List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);