【问题标题】:Converting JSON string to hashmap and array using Jackson使用 Jackson 将 JSON 字符串转换为 hashmap 和数组
【发布时间】:2017-09-08 20:06:43
【问题描述】:

我有一个 json 字符串,我试图解析为 java 对象。我的问题是它包含家具对象的哈希图(或者我理解)和供应商数组。我解析供应商数组没有问题,但无法找出正确解析哈希图的解决方案。

我的 JSON 看起来像:

 {
"furniture": [{
        "table": {
            "price": "200",
            "available": false,
            "dimensions": {
                "height": 5,
                "weight": 20
            }
        }
    },

    {
        "chair": {
            "price": 400,
            "dimensions": {
                "height": 3
            }
        }
    }
],
"vendors": [{
        "id": 3400,
        "name": "Andrew Wlkinson",
        "email": "andrewwilkinson@hmail.com"
    },

    {
        "id": 2344,
        "name": "Daniel Mitchell",
        "email": "danielmitch@hmail.com"
    }
]

}

在我的主要功能中,我正在创建一个映射器并尝试一次解析整个事情,我想这就是问题所在。

ObjectMapper objectMapper = new ObjectMapper();
Data data = objectMapper.readValue(new File("example.json"), Data.class);

Data 类包含作为哈希图的家具和作为数组的供应商。 因此,如果有人能指出我正确的方向或更好的方法,那将不胜感激。

public class Data {
private Vendor[] vendors;
Map<String, Attributes> furniture = new HashMap<String, Attributes>(); 

   public Vendor[] getVendors() {
        return vendors;
    }

 public void setVendors(Vendor[] vendors) {
        this.vendors = vendors;
    }
 public Map<String, Attributes>  getFurniture() {
        return furniture;
    }

 public void setFurniture(Map<String, Attributes> furniture) {
        thisfurniture = furniture;
    }

我得到的错误是

 `Can not deserialize instance of java.util.LinkedHashMap out of START_ARRAY token at [Source: sample.json; line: 2, column: 2] (through reference chain: Data["furniture"])`

【问题讨论】:

  • 请发布 Data 类以及您在编译时或运行时获得的结果。
  • 您提供的JSON无效,请提供有效的JSON。
  • @jordanpg 已将其添加到帖子中

标签: java json dictionary


【解决方案1】:

在你提到的json中,家具代表一个数组。你需要像这样改变它:

{ "furniture" :
 { "table": { 
     "price": 200,
     "available": false,
      "dimensions": {"height":23, "weight":20"}}},
   "chair": {
      "price": 400,
      "dimensions": {"height":3}},

  "vendors":
  [{ "id": 3400,
     "name": "Andrew Wlkinson",
     "email": "andrewwilkinson@hmail.com",
   },

   { "id": 2344,
     "name": "Daniel Mitchell",
     "email": "danielmitch@hmail.com",
   }]}

【讨论】:

  • 这是学校任务,可惜我不能改json
  • 这不是可选的。 Jackson 不会反序列化无效的 JSON。将其放入 IDE 并尝试对其进行格式化。它有多个问题。
猜你喜欢
  • 2016-09-24
  • 1970-01-01
  • 2014-03-10
  • 1970-01-01
  • 2021-04-14
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多