2013-04-11 24 views
0

我想解析一个由Customer对象数组组成的JSON对象。每个客户对象都包含多个键/值对:当事先已知密钥时,使用gson反序列化JSON对象

{ 
    "Customers": 
    [ 
    { 
     "customer.name": "acme corp", 
     "some_key": "value", 
     "other_key": "other_value", 
     "another_key": "another value" 
    }, 
    { 
     "customer.name": "bluechip", 
     "different_key": "value", 
     "foo_key": "other_value", 
     "baa": "another value" 
    } 
    ] 
} 

复杂性在于密钥在事先并不知道。第二个复杂因素是键包含句点(。),这意味着即使当我试图将它们映射到字段时,它也会失败。

我一直在试图将它们映射到客户类:

Customers data = new Gson().fromJson(responseStr, Customers.class); 

,看起来像这样:

public class Customers { 

    public List<Customer> Customers; 

    static public class Customer { 

     public List<KeyValuePair> properties; 
     public class KeyValuePair { 
      String key; 
      Object value; 
     }  
    } 
} 

我的问题是,当我从JSON加载这个类,我客户列表填充,但其属性为空。我怎样才能让GSON处理我不知道密钥名称的事实?

我已经尝试了各种其他方法,包括在客户类中放置HashMap,以取代KeyValuePair类。

回答

1

另一种办法是,你可以从JSON创建一个Map键值,然后查找值,因为该键不知道

Gson gson = new Gson(); 
    Type mapType = new TypeToken<Map<String,List<Map<String, String>>>>() {}.getType(); 
    Map<String,List<Map<String, String>> >map = gson.fromJson(responseStr, mapType); 
    System.out.println(map); 

    Customers c = new Customers(); 

    c.setCustomers(map.get("Customers")); 

    System.out.println(c.getCustomers()); 

修改你的客户类这样

public class Customers { 

public List<Map<String, String>> customers; 

public List<Map<String, String>> getCustomers() { 
    return customers; 
} 

public void setCustomers(List<Map<String, String>> customers) { 
    this.customers = customers; 
} 

} 
+0

这工作!非常感谢 – k2col 2013-04-11 19:53:55