简体   繁体   English

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

[英]Creating array list of java objects from JSON URL with Gson

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? 有人可以帮我修改我的代码吗?

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

A quick look in the Gson User Guide indicates 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 可以序列化任意对象的集合但不能从中反序列化因为用户无法指示生成的对象的类型在反序列化时,Collection必须是特定的泛型类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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