试图通过Spring Boot Rest使用Jackson验证JSON [英] Trying to Validate JSON using Jackson through Spring Boot Rest

查看:330
本文介绍了试图通过Spring Boot Rest使用Jackson验证JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用Spring Boot创建一个RESTful Web服务,它将使用JSON并使用Jackson验证它。

Am trying to create a RESTful Web Service using Spring Boot which will take in a JSON and validate it using Jackson.

这是RESTful Web服务:

Here's the RESTful Web Service:

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);

    }
}

以下是Validator的代码:

Here's the code to the Validator:

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;
    }
}

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

So, when I use a curl to send a valid JSON:

curl -H "Accept: application/json" -H "Content-type: application/json" \ 
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate

我收到以下内容给stdout:

I receive the following to stdout:

{"name":"value"}
true

但是当使用以下curl命令获取无效JSON时(故意删除关闭花括号) ):

But when use the following curl command for invalid JSON (deliberately removed the closing curly brace):

curl -H "Accept: application/json" -H "Content-type: application/json" \
 -X POST -d '{"name":"value"' http://localhost:8080/myservice/validate

我在stdout内收到以下内容:

I receive the following inside stdout:

{"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"

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

Is there a way to ensure exception is handled on the server side but not thrown in stdout and then just have my code respond with:

false

感谢您花时间阅读此内容...

Thanks for taking the time to read this...

推荐答案

想出来!

添加了以下更改:

在@RequestMapping代码部分内:

Inside the @RequestMapping code section:

consumes = "text/plain",
produces = "application/json"

将@RequestBody从Map更改为String payload。

Changed @RequestBody from Map to String payload.

ValidationService类:

ValidationService class:

@RequestMapping(value="/validate", 
                method = RequestMethod.POST, 
                consumes="text/plain", 
                produces="application/json")
public ValidationResponse process(@RequestBody String payload) throws JsonParseException,
                                                                      IOException {
    ValidationResponse response = new ValidationResponse();
    boolean retValue = false;
    retValue = Validator.isValid(payload);
    System.out.println(retValue);
    if (retValue == false) {
        response.setMessage("Invalid JSON");
    }
    else {
        response.setMessage("Valid JSON");
    }
    return response;
}

Validator类:

Validator class:

import java.io.IOException;

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

public class Validator {

    public static boolean isValid(String json) {
        boolean retValue = true;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
            JsonFactory factory = mapper.getFactory();
            JsonParser parser = factory.createParser(json);
            JsonNode jsonObj = mapper.readTree(parser);
            System.out.println(jsonObj.toString());
        }
        catch(JsonParseException jpe) {
            retValue = false;   
        }
        catch(IOException ioe) {
            retValue = false;
        }
        return retValue;
    }
}

ValidationResponse:

ValidationResponse:

public class ValidationResponse {

    public String message;

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

为Content-type使用'text / plain':

Using 'text/plain' for Content-type:

curl -H "Accept: application/json" -H "Content-type: text/plain" -X POST -d \ 
 '{"name":"value"}' http://localhost:8080/myservice/validate

现在,一切正常!摇滚!

Now, everything works! This rocks!

这篇关于试图通过Spring Boot Rest使用Jackson验证JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆