来自Java Pojo的JSON转换错误

时间:2018-06-24 23:00:02

标签: java json

我的userDTO如下所示,并且   我正在尝试将userDTO转换为json字符串并从Controller调用rest API端点,但是被调用的rest API端点抛出错误,因为“数据”不是有效的JSONobject

public  class UserDTO {

 private String userId;
 private String firstname;
 private String lastname;
 private List<Order> orders;
  some more data member plus // setter  / Getters

}

我的控制器类:- [将userDTO转换为json字符串]

 public class OrderController {

    UserDTO userRecord = new UserDTO ();
     //  userRecord some values here

    final HttpStatus httpStatus;
    HttpEntity<?> httpEntity;
    final HttpHeaders headers = new HttpHeaders();
    final ObjectMapper mapper = new ObjectMapper();
    headers.setContentType(MediaType.APPLICATION_JSON);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    String jsonInput;
 // I guess this is the point creating that issue. May be Im doing in wrong way....
    jsonInput = mapper.writeValueAsString(new JSONObject().put("data",userRecord ));
    httpEntity = new HttpEntity<Object>(jsonInput, headers);
     // calling the rest API endpoint          
   ResponseEntity<String> responseEntity = restTemplate.exchange(
                  URL, HttpMethod.POST, httpEntity,
                  String.class,someId);
  }

服务器Sinippet:-

     public MicroserviceResponse createOrder(@PathVariable("cId") final String cId, @RequestBody final String requestBody) throws Exception {
       ObjectMapper mapper = new ObjectMapper();
        requestJSON = new JSONObject(requestBody).getJSONObject("data");
        final String jsonData = requestJSON.toString();
        UserDTO orderSource = mapper.readValue(jsonData, 
       UserDTO .class);
       }

问题:- 称为API [服务器]抛出“数据无效JSONObject。我在这里缺少什么吗?请指导我。

尝试发送以下几种JSON格式

{ 
  "data":{ 
  "username":"test",
  "orderId": "123097R",
  "firstName":"xydz",
  "lastName":"xyzd",
  "email":"xx@gmail.com"
 }
}

1 个答案:

答案 0 :(得分:0)

由于没有提供详细的服务器日志-我假设所提到的错误发生在REST层。

请尝试以下操作-创建有效负载Java类:

public  class RestPayload implements java.io.Serializable {

 private UserDTO data;

 public  UserDTO getUserDTO (){
  return this.data;
 }
  public void setUserDTO(UserDTO data){
   this.data = data;
  }

}

然后将您当前的休息操作修改为:

 @POST 
 public MicroserviceResponse createOrder(@PathVariable("cId") final String cId,  @RequestBody final RestPayload  restPayload ) throws Exception {

        UserDTO orderSource = restPayload.getUserDTO();
 }

更新:

您还可以使用原始JSON并根据需要修改值。

尝试一下-以下代码显示了如何将“数据”作为父对象添加到UserDTO:

    Gson gson = new Gson();
    JsonElement userDtoJsonElement = gson.toJsonTree(userDTO);

    JsonObject dataObject = new JsonObject();
    dataObject.add("data", userDtoJsonElement);

    System.out.println(gson.toJson(dataObject));