从 JSONArray 转换为 ArrayList<CustomObject> - Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21962502/
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
Convert from JSONArray to ArrayList<CustomObject> - Android
提问by stanete
I converted an ArrayList to an JSONArray. How can I convert it back?
我将 ArrayList 转换为 JSONArray。我怎样才能把它转换回来?
The final result must be an ArrayList. Thank you in advance.
最终结果必须是一个 ArrayList。先感谢您。
EDIT:
编辑:
This is how I convert the ArrayList to JSONArray:
这就是我将 ArrayList 转换为 JSONArray 的方式:
String string_object= new Gson().toJson(MyArrayList<OBJECT>);
JSONArray myjsonarray = new JSONArray(string_object);
回答by Purushotham
You can convert your JsonArray or json string to ArrayList<OBJECT>
using Gson library as below
您可以将您的 JsonArray 或 json 字符串转换为ArrayList<OBJECT>
使用 Gson 库,如下所示
ArrayList<OBJECT> yourArray = new Gson().fromJson(jsonString, new TypeToken<List<OBJECT>>(){}.getType());
//or
ArrayList<OBJECT> yourArray = new Gson().fromJson(myjsonarray.toString(), new TypeToken<List<OBJECT>>(){}.getType());
Also while converting your ArrayList<OBJECT>
to JsonArray, no need to convert it to string and back to JsonArray
此外,在将您转换ArrayList<OBJECT>
为 JsonArray 时,无需将其转换为字符串并返回到 JsonArray
JsonArray myjsonarray = new Gson().toJsonTree(MyArrayList<OBJECT>).getAsJsonArray();
Refer Gson API documentationfor more details. Hope this will be helpful.
有关更多详细信息,请参阅Gson API 文档。希望这会有所帮助。
回答by David C Adams
JSONArray is just a subclass of object, so if you want to get the JSONObjects out of a JSONArray into some other form, JSONArray doesn't have any convenient way to do it, so you have to get each JSONObject and populate your ArrayList yourself.
JSONArray 只是 object 的一个子类,因此如果您想将 JSONArray 中的 JSONObjects 转换为其他形式,JSONArray 没有任何方便的方法可以做到这一点,因此您必须自己获取每个 JSONObject 并填充您的 ArrayList。
Here is a simple way to do it:
这是一个简单的方法:
ArrayList<JSONObject> arrayList = new ArrayList(myJSONArray.length());
for(int i=0;i < myJSONArray.length();i++){
arrayList.add(myJSONArray.getJSONObject(i));
}
EDIT:
编辑:
OK, you edited your code to show that you are using GSON. That is a horse of a different color. If you use com.google.gson.JsonArray instead of JSONArray, you can use the Gson.fromJson() method to get an ArrayList.
好的,您编辑了代码以显示您正在使用 GSON。那是一匹不同颜色的马。如果您使用 com.google.gson.JsonArray 而不是 JSONArray,则可以使用 Gson.fromJson() 方法来获取 ArrayList。
Here is a link: Gson - convert from Json to a typed ArrayList
回答by Ted Hopp
Unfortunately, this will require a little work on your part. Gson does not support deserializing generic collections of arbitrary objects. The Gson User Guide topic Serializing and Deserializing Collection with Objects of Arbitrary Typeslist three options for doing what you want. To quote the relevant parts of the guide:
不幸的是,这需要您做一些工作。Gson 不支持反序列化任意对象的泛型集合。Gson 用户指南主题使用任意类型的对象序列化和反序列化集合列出了三个选项来执行您想要的操作。引用指南的相关部分:
You can serialize the collection with Gson without doing anything specific:
toJson(collection)
would write out the desired output. However, deserialization withfromJson(json, Collection.class)
will not work since Gson has no way of knowing how to map the input to the types. Gson requires that you provide a genericised version of collection type infromJson
. So, you have three options:Option 1: Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use
Gson.fromJson()
on each of the array elements. This is the preferred approach. Here is an examplethat demonstrates how to do this.Option 2: Register a type adapter for
Collection.class
that looks at each of the array members and maps them to appropriate objects. The disadvantage of this approach is that it will screw up deserialization of other collection types in Gson.Option 3: Register a type adapter for
MyCollectionMemberType
and usefromJson
withCollection<MyCollectionMemberType>
This approach is practical only if the array appears as a top-level element or if you can change the field type holding the collection to be of typeCollection<MyCollectionMemberType>
.
您可以使用 Gson 序列化集合,而无需执行任何特定操作:
toJson(collection)
将写出所需的输出。但是,反序列化fromJson(json, Collection.class)
不会起作用,因为 Gson 无法知道如何将输入映射到类型。Gson 要求您在fromJson
. 所以,你有三个选择:选项 1:使用 Gson 的解析器 API(低级流解析器或 DOM 解析器 JsonParser)解析数组元素,然后
Gson.fromJson()
在每个数组元素上使用。这是首选方法。这是一个演示如何执行此操作的示例。选项 2:注册一个类型适配器,用于
Collection.class
查看每个数组成员并将它们映射到适当的对象。这种方法的缺点是它会搞砸 Gson 中其他集合类型的反序列化。选项 3:为 注册类型适配器
MyCollectionMemberType
并用于 仅当数组显示为顶级元素或者您可以将保存集合的字段类型更改为 type 时fromJson
,Collection<MyCollectionMemberType>
此方法才实用Collection<MyCollectionMemberType>
。
See the docs for details on each of the three options.
有关三个选项中每一个的详细信息,请参阅文档。
回答by ceph3us
we starting from conversion [ JSONArray -> List < JSONObject > ]
我们从转换开始 [ JSONArray -> List < JSONObject > ]
public static List<JSONObject> getJSONObjectListFromJSONArray(JSONArray array)
throws JSONException {
ArrayList<JSONObject> jsonObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
jsonObjects.add(array.getJSONObject(i++))
);
return jsonObjects;
}
next create generic version replacing array.getJSONObject(i++) with POJO
接下来创建通用版本用 POJO 替换 array.getJSONObject(i++)
example :
例子 :
public <T> static List<T> getJSONObjectListFromJSONArray(Class<T> forClass, JSONArray array)
throws JSONException {
ArrayList<Tt> tObjects = new ArrayList<>();
for (int i = 0;
i < (array != null ? array.length() : 0);
tObjects.add( (T) createT(forClass, array.getJSONObject(i++)))
);
return tObjects;
}
private static T createT(Class<T> forCLass, JSONObject jObject) {
// instantiate via reflection / use constructor or whatsoever
T tObject = forClass.newInstance();
// if not using constuctor args fill up
//
// return new pojo filled object
return tObject;
}
回答by Ibrahem Salah
Try this,
尝试这个,
ArrayList<**YOUCLASS**> **YOURARRAY** =
new Gson().fromJson(oldJSONArray.toString(),
new TypeToken<List<**yourClass**>>(){}.getType());