2012-07-08 63 views
3
创建Java对象的数组列表

我能够下列数据解析为一个Java对象:使用此代码从JSON URL与GSON

{ 
    "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." 
    } 
] 

有人可以帮我修改我的代码吗?

回答

0

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

类别限制

可序列化的任意对象的集合,但不能序列化从它 因为没有办法为用户指示 类型生成的对象反序列化,集必须是一个 特定泛型类型

+0

在这个例子中的问题,我没有看到任何迹象表明这个名单可以包含不同类型的组件(或不同亚型的一个共同的父类型)。 Gson确实具有内置处理功能,用于反序列化到相同类型的事物的列表或数组中。 – 2012-07-08 23:55:02

+0

感谢您的回复。任何关于如何解决此问题的建议? 我应该使用不同的库来解析Json吗? 我应该看看你链接到的用户指南中提到的'TypeToken'吗? – NullPointer 2012-07-08 23:56:16

5

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

由于阵:

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

谢谢布鲁斯,这是完美的。我结束了与列表,但也尝试阵列,他们都工作。 – NullPointer 2012-07-10 09:50:23

+0

谢谢!它适用于ArrayList 。 – herbertD 2014-05-13 08:37:35