在事先不知道密钥时使用 gson 反序列化 JSON 对象

问题描述 投票:0回答:1

我正在尝试解析一个由客户对象数组组成的 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 放在 Customer 类中,代替 KeyValuePair 类。

java json gson
1个回答
1
投票

一种不同的方法是,您可以从 JSON 创建一个键值映射,然后查找值,因为键是未知的

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

}
© www.soinside.com 2019 - 2024. All rights reserved.