2016-04-26 73 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。 –