繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM