[英]JSONArray to ArrayList<MyObject>
Is it possible using json-simple (and no other additional library) to convert a JSONArray
to an ArrayList<MyObject>
? 是否可以使用json-simple (并且不使用其他任何库)将
JSONArray
转换为ArrayList<MyObject>
?
I was not able to find code samples in the documentation nor on SO. 我无法在文档中或SO上找到代码示例。
This is how I do it at the moment (quite a bit complicated): 这是我目前的做法(有点复杂):
for(Iterator iterator = jsonRootObject.keySet().iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
JSONObject jsonEpg = (JSONObject) jsonRootObject.get(key);
JSONArray jsonEpgTags = (JSONArray) jsonEpg.get("tags");
//Iterate tags
for(int i = 0; i < jsonEpgTags.size(); i++) {
JSONObject jsonEpgTag = (JSONObject) jsonEpgTags.get(i);
final String tagId = (String) jsonEpgTag.get("id");
String name = (String) jsonEpgTag.get("name");
EpgJsonTagValue jsonTagValue = new EpgJsonTagValue();
jsonTagValue.tagId = tagId;
jsonTagValue.name = name;
result.add(jsonTagValue);
}
}
My "POJO": 我的“ POJO”:
public class EpgJsonTagValue {
private String tagId;
private String name;
public String getTagId() {
return tagId;
}
public void setTagId(String id) {
this.tagId = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return "TagId: " + tagId
+ ", Name: " + name;
}
}
You join
the elements using a separator
String
, then split
them to get an array, then pass this array to Arrays.asList
which will be passed to the constructor of ArrayList
. 您
join
使用的元素separator
String
,然后split
他们得到一个数组,然后通过这个数组Arrays.asList
将被传递给的构造函数ArrayList
。
public static ArrayList<Object> JSONArray2ArrayList(JSONArray input, Class c) {
return new ArrayList<c>(Arrays.asList(input.join(separator).split(separator)));
}
You dont have to iterate JsonArray object to build a list. 您不必迭代JsonArray对象即可构建列表。 Its already implements List interface so just type cast it, like below
它已经实现了List接口,所以只需将其强制转换,如下所示
List<UserObject> result = (List<UserObject>) jsonArray;
Please try and let me know. 请尝试让我知道。
This will work for sure!! 这肯定可以工作!!
List<EpgJsonTagValue> epgJsonTagValueList = (List<EpgJsonTagValue>)jsonEpgTags ;
Or if you want an ArrayList then this will work: 或者,如果您想要一个ArrayList,那么它将起作用:
ArrayList<EpgJsonTagValue> epgJsonTagValueList = (ArrayList<EpgJsonTagValue>)jsonEpgTags ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.