尝试通过 Spring Boot Rest 使用 Jackson 验证 JSON

Pac*_*ver 5 java json spring-mvc jackson spring-boot

我正在尝试使用 Spring Boot 创建一个 RESTful Web 服务,它将接收 JSON 并使用 Jackson 对其进行验证。

这是 RESTful Web 服务:

import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.Gson;

@RestController
@RequestMapping("/myservice")
public class ValidationService {    

    @RequestMapping(value="/validate", method = RequestMethod.POST)
    public void validate(@RequestBody Map<String, Object> payload) throws Exception {
        Gson gson = new Gson();
        String json = gson.toJson(payload); 
        System.out.println(json);
        boolean retValue = false;

        try {
            retValue = Validator.isValid(json);
        } 
        catch(Throwable t) {
            t.printStackTrace();
        }
        System.out.println(retValue);

    }
}
Run Code Online (Sandbox Code Playgroud)

这是验证器的代码:

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Validator {

    public static boolean isValid(String json) {
        boolean retValue = false;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
            JsonParser parser = objectMapper.getFactory().createParser(json);
            while (parser.nextToken() != null) {}
            retValue = true;
            objectMapper.readTree(json);
        }catch(JsonParseException jpe) {
            jpe.printStackTrace();
        }
        catch(IOException ioe) {

        }
        return retValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,当我使用curl发送有效的JSON时:

curl -H "Accept: application/json" -H "Content-type: application/json" \ 
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate
Run Code Online (Sandbox Code Playgroud)

我收到以下标准输出:

{"name":"value"}
true
Run Code Online (Sandbox Code Playgroud)

但是当对无效的 JSON 使用以下curl命令时(故意删除右大括号):

curl -H "Accept: application/json" -H "Content-type: application/json" \
 -X POST -d '{"name":"value"' http://localhost:8080/myservice/validate
Run Code Online (Sandbox Code Playgroud)

我在标准输出中收到以下内容:

{"timestamp":1427698779063,
 "status":400,"error":
 "Bad Request",
 "exception":"org.springframework.http.converter.HttpMessageNotReadableException",
 "message":"Could not read JSON: 
 Unexpected end-of-input: expected close marker for OBJECT 
 (from [Source: java.io.PushbackInputStream@1edeb3e; line: 1, column: 0])\n
 at [Source: java.io.PushbackInputStream@1edeb3e; line: 1, column: 31]; 
 nested exception is
 com.fasterxml.jackson.core.JsonParseException: 
 Unexpected end-of-input: expected close marker for OBJECT 
 (from [Source: java.io.PushbackInputStream@1edeb3e; line: 1, column: 0])\n 
 at [Source: java.io.PushbackInputStream@1edeb3e; line: 1, column: 31]",
 "path":"/myservice/validate"
Run Code Online (Sandbox Code Playgroud)

有没有办法确保异常在服务器端处理但不会抛出到标准输出中,然后让我的代码响应:

false
Run Code Online (Sandbox Code Playgroud)

感谢您抽时间阅读...

sod*_*dik 0

我的猜测是问题出在@RequestBody Map<String, Object> payload你的控制器的声明上。Spring MVC 需要将请求正文转换为Map,因此如果请求不包含正确的 JSON,则会失败。

但是,由于您想接受任何输入,因此可以使用@RequestBody String payload代替,作为奖励,您可以摆脱 GSON 到字符串的转换:)