gpt4 book ai didi

java - 使用 Gson 从 JSON URL 创建 java 对象的数组列表

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:53:15 25 4
gpt4 key购买 nike

我能够将以下数据解析为 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;
}

作为 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));
}
}

关于java - 使用 Gson 从 JSON URL 创建 java 对象的数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11387231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com