【问题标题】:How to send complex JSON structure from angular to spring controller如何将复杂的 JSON 结构从 Angular 发送到 Spring 控制器
【发布时间】:2016-04-26 10:38:51
【问题描述】:

我的角度控制器中有一个如下所示的 JSON,我需要将其发布到 Spring 控制器。

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);
});

在我的 Spring 控制器中

@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 中的某些内容吗?

【问题讨论】:

  • 您是否尝试过从其他客户端(例如邮递员)发送请求?
  • 您是否尝试过您发布的确切示例?
  • @Nayan 没有。我没有使用任何其他客户端
  • @sura2k 是的,完全相同的例子。
  • 我的 pojo 课程正确吗?

标签: java angularjs json spring


【解决方案1】:

您可能需要将 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);
  }
}

【讨论】:

  • 这适用于复杂的 JSON 吗?就像我在问题中提到的那样?
  • 肯定会的。你在这里得到了完整的 json,你可以使用你制作的模型将它分解成单独的字符串和对象。
  • 我刚刚测试过.. 只有当我没有像示例中那样的嵌套 JSON 时它才有效。
猜你喜欢
  • 2014-10-20
  • 2016-08-05
  • 2018-02-28
  • 2021-03-17
  • 2018-02-15
  • 2012-09-09
  • 2018-07-12
  • 2012-01-29
  • 2018-01-18
相关资源
最近更新 更多