如何使用 Gson 将 JSONArray 转换为列表? [英] How to convert JSONArray to List with Gson?

查看:122
本文介绍了如何使用 Gson 将 JSONArray 转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Android 项目中,我试图将接收到的 JSONArray 转换为列表.在 this SO answer 的帮助下,我得到了一个再远一点.我现在有以下代码:

In my Android project I'm trying to convert a received JSONArray to a List. With the help of this SO answer I got a bit further. 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);

不幸的是,它在最后一行抱怨 Gson 类型中的 fromJson(String, Type) 方法不适用于参数 (JSONArray, Type).我真的不知道如何解决这个问题.

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.

有人知道我该如何解决这个问题吗?

Does anybody know how I can solve this?

推荐答案

如果你看到那里的答案,你会注意到 fromJson() 方法中的第一个参数是一个 String(json 对象).尝试像这样在 JsonArray 上使用 toString() :-

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:-

List<MyModel> myModelList = gson.fromJson(jsonArray.toString(), listType);

这篇关于如何使用 Gson 将 JSONArray 转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆