2013-04-11 50 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