使用Jackson将JSON字符串转换为hashmap和数组

时间:2017-09-08 20:06:43

标签: java json dictionary

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

我的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);

数据类包含作为散列图的家具和作为数组的供应商。  因此,如果有人能指出我正确的方向或更好的方法,那将非常感激。

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"])`

1 个答案:

答案 0 :(得分:0)

在你提到的json中,furniture表示一个数组。你需要改变它:

{ "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",
   }]}