使用 Gson 从 JSON URL 创建 java 对象的数组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11387231/
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
Creating array list of java objects from JSON URL with Gson
提问by NullPointer
I am able to parse the following data into a java object:
我能够将以下数据解析为一个 java 对象:
{
"name": "testname",
"address": "1337 455 ftw",
"type": "sometype",
"notes": "cheers mate"
}
using this code:
使用此代码:
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();
}
}
}
But now I want to store a list of these objects out of the following JSON String:
但现在我想从以下 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."
}
]
Could someone help me modify my code to do this?
有人可以帮我修改我的代码来做到这一点吗?
回答by Programmer Bruce
You could specify the type to deserialize into as an array or as a collection.
您可以指定要反序列化为数组或集合的类型。
As Array:
作为数组:
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;
}
As List:
作为列表:
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));
}
}
回答by magiconair
A quick look in the Gson User Guideindicates that this might not be possible since the deserializer doesn't know the type of the elements since you could have elements of different types in the array.
快速查看Gson 用户指南表明这可能是不可能的,因为解串器不知道元素的类型,因为数组中可能有不同类型的元素。
Collections Limitations
Can serialize collection of arbitrary objects but can not deserialize from it Because there is no way for the user to indicate the type of the resulting object While deserializing, Collection must be of a specific generic type
集合限制
可以序列化任意对象的集合但不能反序列化因为用户无法指示结果对象的类型反序列化时,集合必须是特定的泛型类型