【问题标题】:JSON.stringify from typescript/javascript do not match json-String param/request-body in Java controller来自 typescript/javascript 的 JSON.stringify 与 Java 控制器中的 json-String param/request-body 不匹配
【发布时间】:2021-07-30 04:31:51
【问题描述】:

我正在使用 jdk 1.8。我在 java 控制器中有一个休息端点:

@PostMapping("/filters")
public ResponseEntity<StatsDTO> listWithFilter(
      @RequestBody(required = false) String filter
) {
try { 
   ...............
}
}

针对上述控制器的测试 sn-p 正在通过(在此 sn-p 中返回预期结果):

@Test
public void findReferralTest15() throws IOException {

   String result = webClient.post()
        .uri(endpoint(helper.entity + "/filters"))
        .contentType(MediaType.APPLICATION_JSON)
        .header(HttpHeaders.AUTHORIZATION, clientUser())
        .body(BodyInserters.fromObject(buildJsonForQuery15()))
        .exchange()
        .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)
        .expectStatus().isOk()
        .expectBody(String.class).returnResult().getResponseBody();


   ObjectMapper mapper = new ObjectMapper();
   ResponseList referralList = mapper.readValue(result, ResponseList.class);
} 

public String buildJsonForQuery15() {
    String json = "{\"billType\":{\"INTAKE\":true}}";
    return json;
}

现在,当我尝试与前端集成时(打字稿上的 Angular 7),我必须执行 JSON.stringify 两次 (到要作为 requestbody 提交的 json 对象或过滤器) 使其与后端一起工作。我得到 null 否则作为 java 控制器端的 "filter" (在请求正文中)的值。

所以使用 double JSON.stringify 从我们的前端提交的结果是 (WHEN IT WORKS):

"{\"billType\":{\"INTAKE\":true}}"

所以对于 single JSON.stringify 从我们的端提交的结果是 (WHEN IT DOESN'T WORK)

{"billType":{"INTAKE":true}}

问题:java 控制器中 requestBody "filter" 的数据类型应该是什么才能使其与单个 JSON.stringify 一起使用?

我尝试将 json.org.JsonObject 作为“过滤器”的数据类型,但没有任何区别。

提前致谢。

前端sn-p:

const fullUrl = `${this.referralsUrl}/filters?first=${first}&max=${max}`;
const headerDict = {
  "Content-Type": "application/json; charset=utf-8",
  Accept: "application/json",
  "Access-Control-Allow-Headers": "Content-Type"
};
const headers = new HttpHeaders(headerDict);

 if (filters) {

  const requestBody = JSON.stringify(filters);
  return this.http
    .post<Page<ClinAssistReferral>>(fullUrl, JSON.stringify(requestBody), { headers })
    .pipe(
      map((data: any) => {
      ...........
      }
}

【问题讨论】:

    标签: java json angularjs typescript rest


    【解决方案1】:

    如果正文不是动态的,则首选为请求创建 DTO。

    如果body是动态的,我建议你试试jackson的JsonNode。看看这个库能不能

    import com.fasterxml.jackson.databind.JsonNode;
    ...
    
    @PostMapping("/filters")
    public ResponseEntity<StatsDTO> listWithFilter(
          @RequestBody(required = false) JsonNode filter
    ) {
       try { 
          var intake = filter.get("billType").get("INTAKE").asBoolean()
          ...............
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-14
      相关资源
      最近更新 更多