2

我正在开发一个 API,我在其中接收一些与文章相关的数据作为 POST 请求。我的接收器如下:

@ApiOperation(value = "Add a new Article", produces = "application/json")
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ResponseEntity createPost(@RequestBody String postContent) {
    try {
        // Here I need to conver the postContent to a POJO
        return new ResponseEntity("Post created successfully", HttpStatus.OK);
    } catch (Exception e) {
        logger.error(e);
        return responseHandler.generateErrorResponseJSON(e.getMessage(), 
        HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

现在它适用于简单的请求,例如:

{
  "id": "1",
  "title": "This is the Post Title",
  "body": "This is the Post Body",
  "authorName": "Test",
  "tagList": [
    "tag-1",
    "tag-2",
    "tag-3"
  ]
}

但在实际场景中,我会收到一个 HTML 内容,作为请求 JSON 中“body”键的值,它可以有“”、<、> 或很多东西。然后字符串到 JSON 的转换将失败。是否有任何 api、库或示例,我可以将 HTML 内容作为 JSON 键的值。

以下是我的输入请求,其中代码无法将 JSON 解析为对象:

{
  "menuId": "1",
  "title": "This is the Post Title",
  "body": "<p style="text-align:justify"><span style="font-size:16px"><strong>Mediator pattern</strong> is a Behavioral Design pattern. It is used to handle complex communications between related Objects, helping by decoupling those objects.</span></p>",
  "authorName": "Arpan Das",
  "tagList": [
    "Core Java",
    "Database",
    "Collection"
  ]
}

现在我如何解析 json 就像:

public Post parsePost(String content) {
        Post post = new Post();
        JSONParser jsonParser = new JSONParser();
        try {
            JSONObject jsonObject = (JSONObject) jsonParser.parse(content);
            post.setMenuId((Integer) jsonObject.get(Constant.MENU_ID));
            post.setTitle((String) jsonObject.get("title"));
            post.setBody((String) jsonObject.get("body"));
            post.setAuthorName((String) jsonObject.get("authorName"));
            post.setAuthorId((Integer) jsonObject.get("authorId"));
            post.setTagList((List) jsonObject.get("tag"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return post;
    }

它给出了一个解析异常:

Unexpected character (t) at position 77.

我用来解析 JSON 的库是:

 <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>
4

0 回答 0