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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:24:33  来源:igfitidea点击:

How to convert JSONArray to List with Gson?

javaandroidjsongsonarrays

提问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);