[英]Creating array list of java objects from JSON URL with Gson
我能夠將以下數據解析為java對象:
{
"name": "testname",
"address": "1337 455 ftw",
"type": "sometype",
"notes": "cheers mate"
}
使用此代碼:
public class Test
{
public static void main (String[] args) throws Exception
{
URL objectGet = new URL("http://10.0.0.4/file.json");
URLConnection yc = objectGet.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
Gson gson = new Gson();
try {
DataO data = new Gson().fromJson(in, DataO.class);
System.out.println(data.getName());
}catch (Exception e) {
e.printStackTrace();
}
}
}
但是現在我想要從以下JSON字符串中存儲這些對象的列表:
[
{
"name": "testname",
"address": "1337 455 ftw",
"type": "sometype",
"notes": "cheers mate"
},
{
"name": "SumYumStuff",
"address": "no need",
"type": "clunkdroid",
"notes": "Very inefficient but high specs so no problem."
}
]
有人可以幫我修改我的代碼嗎?
您可以將要反序列化的類型指定為數組或集合。
作為數組:
import java.io.FileReader;
import com.google.gson.Gson;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
Data0[] data = new Gson().fromJson(new FileReader("input.json"), Data0[].class);
System.out.println(new Gson().toJson(data));
}
}
class Data0
{
String name;
String address;
String type;
String notes;
}
如清單:
import java.io.FileReader;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
List<Data0> data = new Gson().fromJson(new FileReader("input.json"), new TypeToken<List<Data0>>(){}.getType());
System.out.println(new Gson().toJson(data));
}
}
在Gson用戶指南中快速查看表明這可能是不可能的,因為反序列化器不知道元素的類型,因為您可以在數組中包含不同類型的元素。
收藏限制
可以序列化任意對象的集合但不能從中反序列化因為用戶無法指示生成的對象的類型在反序列化時,Collection必須是特定的泛型類型
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.