使用Gson从JSON URL创建java对象的数组列表
我能够将以下数据解析为java对象:使用Gson从JSON URL创建java对象的数组列表,java,json,list,parsing,gson,Java,Json,List,Parsing,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 = n
{
"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));
}
}
导入java.io.FileReader;
导入java.util.List;
导入com.google.gson.gson;
导入com.google.gson.reflect.TypeToken;
公共类GsonFoo
{
公共静态void main(字符串[]args)引发异常
{
List data=new Gson().fromJson(new FileReader(“input.json”)、new TypeToken(){}.getType());
System.out.println(新的Gson().toJson(数据));
}
}
在示例问题中,我看不到任何迹象表明列表可能包含不同类型(或公共父类型的不同子类型)的组件。Gson确实有内置的处理功能,可以将相同类型的内容反序列化到列表或数组中。谢谢您的回复。关于如何解决这个问题,有什么建议吗?我应该使用不同的库来解析Json吗?我应该看看你链接到的用户指南中提到的这个“TypeToken”吗?谢谢Bruce,这太完美了。我最终选择了这个列表,但也尝试了这个数组,它们都成功了。