我正在尝试使用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);
}
}
以下是验证器的代码:
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时:
curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"}' http://localhost:8080/myservice/validate
我从stdout接收到以下内容:
{"name":"value"}
true
当我们使用以下curl命令解析无效的JSON(故意删除了右花括号):
curl -H "Accept: application/json" -H "Content-type: application/json" \
-X POST -d '{"name":"value"' http://localhost:8080/myservice/validate
我收到以下stdout输出:
我在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中抛出异常,然后只需让我的代码响应:
false
感谢您花时间阅读本文...
Map<String, Object> payload
需要有效的JSON格式...如果输入有误,你会如何映射到map上?不过,试着将其改为简单的String payload
,反正你已经在验证字符串了。 - sodik