gpt4 book ai didi

java - 验证 Json 请求架构

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:32 25 4
gpt4 key购买 nike

所以我有一个包含这个方法的 Controller 类:

    @RequestMapping(value = "/x", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<MyRepsonseClass> get(
@ApiParam(value = "x", required = true) @Valid @RequestBody MyRequestClass request
) throws IOException {
//yada yada my logic here
return something;
}

Json 请求自动映射到 MyRequestClass.java

这是这个类的样子:

@lombok.ToString
@lombok.Getter
@lombok.Setter
@JsonInclude(JsonInclude.Include.NON_EMPTY)
@ApiModel(description = "description")
public class MyRequestClass {
private List<SomeClass> attribute1;
private SomeOtherClass attribute2;
private YetAnotherClass attribute3;
}

这是一个有效的 json 请求的例子:

{
"attribute1": [
{
"key":"value"
}
],
"attribute3": {
"key":"value"
}
}

现在,我的要求是当请求包含 MyRequestClass.java 中不存在的属性时返回错误消息。

因此:

{
"attribute1": [
{
"key":"value"
}
],
"attribute_that_doesnt_exist": {
"key":"value"
}
}

现在它没有抛出任何错误。相反,它只是不将该属性映射到任何东西。是否有我可以利用的注释可以快速实现这一点?谢谢。

最佳答案

创建自定义反序列化器:

public class MyRequestClassDeserializer extends JsonDeserializer<MyRequestClass> {
@Override
public MyRequestClass deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
MyRequestClass mrc = new MyRequestClass();
ObjectMapper mapper = new ObjectMapper();
JsonToken currentToken = null;
while((currentToken = jsonParser.nextValue()) != null) {
if(currentToken.equals(JsonToken.END_OBJECT)
|| currentToken.equals(JsonToken.END_ARRAY))
continue;
String currentName = jsonParser.getCurrentName();
switch(currentName) {
case "attribute1":
List<SomeClass> attr1 = Arrays.asList(mapper.readValue(jsonParser, SomeClass[].class));
mrc.setAttribute1(attr1);
break;
case "attribute2":
mrc.setAttribute2(mapper.readValue(jsonParser, SomeOtherClass.class));
break;
case "attribute3":
mrc.setAttribute3(mapper.readValue(jsonParser, YetAnotherClass.class));
break;
// <cases for all the other expected attributes>
default:// it's not an expected attribute
throw new JsonParseException(jsonParser, "bad request", jsonParser.getCurrentLocation());
}
}
return mrc;
}
}

并将此注释添加到您的 MyRequestClass 类:@JsonDeserialize(using=MyRequestClassDeserializer.class)

唯一的“问题”是手动反序列化 json 可能很麻烦。我会为你的案例编写完整的代码,但我现在还不够好。我可能会在未来更新答案。

编辑:完成,现在是工作代码。我认为它更复杂。

关于java - 验证 Json 请求架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44059191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com