JSON对象不正确,并导致HttpException

问题描述 投票:0回答:1

我正在尝试测试此方法:

private ServiceApiMetadata getConfig(final HttpServletRequest request, final String path)
    throws IOException {
  final Schema schema;
  try (final InputStream inStream = this.getClass().getResourceAsStream(path)) {
    final JSONObject origSchema = new JSONObject(new JSONTokener(inStream));
    if (isGoldStar()) {
      origSchema.getJSONObject("properties")
          .getJSONObject("notifications")
          .getJSONObject("properties")
          .getJSONObject("topic")
          .put("pattern", "^[0-9A-Za-z-.]*$");
    }
    schema = SchemaLoader.load(origSchema);
  }

  final ServiceApiMetadata config;
  try (final BufferedReader reader = request.getReader()) {
    final JSONObject json = new JSONObject(new JSONTokener(reader));
    schema.validate(json);
    config = ServiceApiMetadata.read(json);
  } catch (final ValidationException e) {
    _logger.debug(e.getMessage());
    if (e.getLocation().contains("#/properties/notifications")) {
      throw new ServiceApiException(ServiceApiError.MALFORMED_NOTIFICATIONS_ERROR,
          ServiceApiErrorMessage.MALFORMED_JSON);
    } else {
      throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
    }
  } catch (final JSONException e) {
    _logger.debug(e.getMessage());
    throw new ServiceApiException(ServiceApiError.MALFORMED_JSON);
  }

  return config;
}

由于是私有的,所以我在课堂上创建了以下方法:

@TestOnly
protected void runGetConfig(final HttpServletRequest request, final String schemaPath) throws IOException {
  final ServiceApiMetadata conf = getConfig(request, schemaPath);
}

[运行测试时getConfig()引发异常。问题是,当final JSONObject json = new JSONObject(new JSONTokener(reader));行出现此异常时:

HttpException(400,{"status_code":400,"error_code":"MalformedJson","uri":"uri","message":"MalformedJson"},null)

我也在日志中看到此错误:

at 0 [character 1 line 1]

对于HttpServletRequest,我正在使用org.springframework.mock.web.MockHttpServletRequest.MockHttpServletRequest(),如下所示:

final MockHttpServletRequest request = new MockHttpServletRequest();

是否有可能创建了错误的reader,这反过来又意味着JSONObject不正确,如果是,我该如何解决呢?

其他信息我在MockHttpServletRequest中添加了一个正文,但问题仍然相同。我添加了一些日志记录,如下所示:

final JSONObject rawSchema = new JSONObject(new JSONTokener(inputStream));
      _logger.info("rawSchema: " + rawSchema);
      if (isPulsar()) {
        rawSchema.getJSONObject("properties")
            .getJSONObject("notifications")
            .getJSONObject("properties")
            .getJSONObject("topic")
            .put("pattern", "^[0-9A-Za-z-._:/]*$");
      }
      schema = SchemaLoader.load(rawSchema);
    }

    final ServiceApiContainerMetadata conf;
    try (final BufferedReader reader = request.getReader()) {
      _logger.info("reader: " + reader);
      _logger.info("JSONTokener(reader): " + new JSONTokener(reader.readLine()));
      final JSONObject json = new JSONObject(new JSONTokener(reader.readLine()));

它在输出中显示了这个:

rawSchema: {VALID JSON STRUCTURE. IT'S TOO BIG TO INCLUDE IN THIS QUESTION}
reader: java.io.BufferedReader@4c4d27c8
JSONTokener(reader):  at 0 [character 1 line 1]

MockHttpServletRequest上的信息

我的MockHttpServletRequest的正文包含Lorem ipsum文本。如果在我的BufferedReader下添加以下代码,该文本将打印到控制台。最终的JSONObject json = new JSONObject(new JSONTokener(reader.readLine()));so the malformed JSON error in myHttpException`也不足为奇。

while ((strCurrentLine = reader.readLine()) != null) {
  _logger.info("reader: " + strCurrentLine);
}

这可能是我的代码中的错误吗?实际上final JSONObject json = new JSONObject(new JSONTokener(reader.readLine()));应该是final JSONObject json = new JSONObject(schema);吗?如果我尝试可以看到,代码现在到达schema.validate(json);,但是有12 schema violations found。我看不到这些是什么。另一个想法是主体应该为JSON吗?

java json servlets httpexception
1个回答
0
投票

如果仅执行request = new MockHttpServletRequest();,则请求将没有正文,而读取器将没有数据。

您可以使用MockMvcRequestBuilders创建一个完整的请求。

request = MockMvcRequestBuilders.get("/message")
  .contentType(MediaType.TEXT_PLAIN)
  .content("{... json body ...}")
  .buildRequest(context);
© www.soinside.com 2019 - 2024. All rights reserved.