2014-06-11 17 views
2

我需要將自定義對象的地圖Map<String, Set<Result>>從前端發送到後端。如何使用@RequestBody從JSON綁定自定義對象的地圖

所以我認爲應該可以構建JSON,通過Ajax將其發送給控制器,並通過@RequestBody註釋將其接收到控制器中,該註釋應該將json綁定到對象。對?

控制器:

@RequestMapping(value = "/downloadReport", method = RequestMethod.POST) 
public ResponseEntity<byte[]> getReport(@RequestBody Map<String, Set<Result>> resultMap) 
{ 
    Context context = new Context(); 
    context.setVariable("resultMap", resultMap); 
    return createPDF("pdf-report", context); 
} 

JSON:

{ 
    "result": [ 
    { 
     "id": 1, 
     "item": { 
     "id": 3850, 
     "name": "iti" 
     }, 
     "severity": "low", 
     "code": "A-M-01", 
     "row": 1, 
     "column": 1, 
     "description": "Miscellaneous warning" 
    } 
    ] 
} 

型號:

public class Result { 
    private Integer id; 
    private Item item; 
    private String severity; 
    private String code; 
    private Integer row; 
    private Integer column; 
    private String description; 
    //getter & setters 
    //hashCode & equals 
} 
public class Item { 
    private Integer id; 
    private String name; 
    //getter & setters 
} 

發送經過這樣一個JSON像上面阿賈克斯我從瀏覽器收到錯誤消息:

The request sent by the client was syntactically incorrect 

如果我改變JSON發送空集像下面那麼它的工作原理,但當然,我的地圖都有空集:

{"result": []} 

所以,爲什麼我不能夠接收與組對象的填充地圖?爲什麼綁定/解組不能按預期工作,以及我應該如何使其生效?

說明: 我正在使用Jackson庫和編組爲其他情況@ResponseBody工作正常。問題是通過@RequestBody取消編組和綁定對象。

回答

1

爲了讓傑克遜正確地反序列化您的自定義類,您需要提供@JsonCreator帶註釋的構造函數,該構造函數遵循java doc中定義的規則之一。因此,對於你Item類可能是這樣的:

@JsonCreator 
public Item(@JsonProperty("id") Integer id, 
      @JsonProperty("name") String name) { 
    this.id = id; 
    this.name = name; 
} 
1

你必須以不同的方式處理地圖, 首先創建包裝類

public MyWrapperClass implements Serializable { 
    private static final long serialVersionUID = 1L; 
    Map<String, List<String>> fil = new HashMap<String, List<String>>(); 
    // getters and setters 
    } 

,那麼你應該在控制器的請求,

@PostMapping 
    public Map<String,List<String>> get(@RequestBody Filter filter){ 
    System.out.println(filter); 
    } 

Json請求應該像

{ 
     "fil":{ 
      "key":[ 
      "value1", 
      "value2" 
      ], 
      "key":[ 
      "vakue1" 
      ] 
     } 
    } 
相關問題