2016-04-26 72 views
1

我在我的角度控制器中有一個像下面這樣的JSON,我需要發佈到Spring控制器。如何發送複雜的JSON結構從角度到彈簧控制器

var items={"A":"aa", 
      "B":"bb", 
      "C":{"D":"dd", "E":"ee"} 
      }; 

$http.post('localhost:8082/ProjectName/posting',items) 
.success(function(data,status,headers, config){ 
    alert("success"); 
}) 
.error(function(error){ 
    alert(error); 
}); 

在我的春節控制器

@RestController 
public class ForPost{ 
    @RequestMapping(value="/posting",method=RequestMethod.POST) 
    public @ResponseBody List forPosting(@RequestBody PostingModel postingModel){ 
    System.out.println("Print all values received"); 
    . 
    . 
    . 
    . 
    } 
} 

我想對於這種嵌套JSON的,我需要嵌套POJO。 類似:

public class PostingModel{ 
String A; 
String B; 
POJOForC C; 
/* getter setter below*/ 
} 

puublic class POJOForC{ 
String D; 
String E; 
/* getter setter below*/ 
} 

我收到錯誤消息:通過客戶端發送的請求是語法不正確()。 我接受了正確的值嗎?需要修復POJO中的某些內容?

+1

你試過送從靜止客戶e.g郵遞員的要求? – Nayan

+0

您是否嘗試過發佈的確切示例? – sura2k

+0

@Nayan no。我沒有使用任何休息客戶端 –

回答

0

你可能會需要序列化,如下JSON:

$http.post('localhost:8082/ProjectName/posting',JSON.Stringify(items)) 
.success(function(data,status,headers, config){ 
    alert("success"); 
}) 
.error(function(error){ 
    alert(error); 
}); 

那麼模型接收JSON爲:

public class PostingModel { 
    String reqJson; 
} 

@RestController 
public class ForPost{ 
    @RequestMapping(value="/posting",method=RequestMethod.POST) 
    public @ResponseBody List forPosting(@RequestBody PostingModel postingModel){ 

    //You would need to parse the json here to retrieve the objects 
    //Use GSON or Jackson to parse the recieved json. 
     JSONObject json = JSONObject.fromObject(postingModel.reqJson); 
    } 
} 
+0

這是否適用於複雜的JSON?就像我在我的問題中提到的那個? –

+0

肯定會。你可以在這裏得到完整的json,你可以使用你創建的模型將它分解成單獨的字符串和對象。 – Sajal

+0

我剛纔測試..它只適用於當我沒有像例子中嵌套的JSON。 –