【问题标题】:Creating array list of java objects from JSON URL with Gson使用 Gson 从 JSON URL 创建 java 对象的数组列表
【发布时间】:2012-07-08 09:21:26
【问题描述】:

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

有人可以帮我修改我的代码来做到这一点吗?

【问题讨论】:

    标签: java json list parsing gson


    【解决方案1】:

    您可以将要反序列化的类型指定为数组或集合。

    作为数组:

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

    【讨论】:

    • 谢谢布鲁斯,这太完美了。我最终选择了 List,但也尝试了 Array,它们都有效。
    【解决方案2】:

    快速查看Gson User Guide 表明这可能是不可能的,因为反序列化器不知道元素的类型,因为数组中可能有不同类型的元素。

    集合限制

    可以序列化任意对象的集合但不能反序列化 从它因为没有办法让用户指示类型 结果对象反序列化时,Collection 必须是 特定的泛型类型

    【讨论】:

    • 在示例问题中,我没有看到任何迹象表明该列表可能包含不同类型的组件(或常见父类型的不同子类型)。 Gson 确实具有用于反序列化为相同类型事物的列表或数组的内置处理。
    • 感谢您的回复。关于我将如何解决这个问题的任何建议?我应该使用不同的库来解析 Json 吗?我应该查看您链接到的用户指南中提到的这个“TypeToken”吗?
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多