2014-01-31 52 views
0

我有一對Java類,第一個是第二個實例的容器。容器類有一個ID和項目的列表,如:Jackson爲一個數組中的項目序列化一個鍵

public class Container { 
     String id = "123"; 
     ArrayList<Item> items = new ArrayList<Item>(); 
    ... 
    } 

和項目類,如:

public class Item { 
     String id = "123123"; 
     String notes = "what a day"; 
     ... 
    } 

當我序列化,我得到的是這樣的:

{ "id" : "123", 
    "items" : [ { 
     "id" : "123123", 
     "notes" : "what a day" 
     }, { 
     "id" : "456456", 
     "notes" : "what a night" 
     } 
     ] 
    } 

但是,我想要的是:

{ 
     "id": "123", 
     "items": [ 
      { 
      "123123": [ 
       { 
       "notes": "what a day" 
       } 
      ], 
      "456456": [ 
       { 
       "notes": "what a night" 
       } 
      ] 
      } 
     ] 
    } 

其中來自Item類的「id」是「items」數組中元素的標識符。 java類結構將如何改變,或者jackson會給出什麼指令來實現所需的結構?

回答

0

看一看http://jsonlint.com/

由於JSON是一套name/value對你會得到這個錯誤

Parse error on line 4: 
...: [  "123123": {   "not 
----------------------^ 
Expecting '}', ',', ']' 

如果你想擁有的name/value雙你總是可以寫出動態keys的JSON在你的程序邏輯(不是傑克遜)

+0

很好的捕獲 - 我糾正了我真正想要的例子。 – user2037942

+0

所以你想要名稱/值對的名稱是動態的?如果是的話,我已經更新了我的答案 –

相關問題