【问题标题】:Deserializing a JSON object using gson when keys are now known in advance当密钥现在提前知道时,使用 gson 反序列化 JSON 对象
【发布时间】:2013-04-11 17:12:28
【问题描述】:

我正在尝试解析由客户对象数组组成的 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 处理我不知道键名的事实?

我尝试了各种其他方法,包括在 Customer 类中放置一个 HashMap 来代替 KeyValuePair 类。

【问题讨论】:

    标签: java json gson


    【解决方案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;
    }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 2014-10-06
      • 2014-03-27
      相关资源
      最近更新 更多