gpt4 book ai didi

java - Jackson 解析中对象值为 null

转载 作者:行者123 更新时间:2023-11-30 03:27:08 28 4
gpt4 key购买 nike

我正在使用 Jackson 库并试图实现提到的 here

BaseOperationRequest.java

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "command"
)
@JsonSubTypes({
@JsonSubTypes.Type(name = "ZADD", value = ZAddBaseOperationRequest.class)
})
public class BaseOperationRequest {
public short operationId;
public Command command;
public String gameId;
public String key;
}

ZAddBaseOperationRequest.java

public class ZAddBaseOperationRequest extends BaseOperationRequest{
public Map<String, Double> members;
}

Command.java

public enum Command{
ZADD,
HSET
}

当我尝试从 REST 调用传递对象时,问题就出现了,如下所示:

@RestController
public class MyController{
//keeping just for now as GET, will change it to POST and take it in RequesBody later on
@RequestMapping(value = "/process/{object}", method = RequestMethod.GET, produces = "application/json")
public @ResponseBody ResponseEntity process(@Pathvariable String object){
System.out.println(object);//I am getting this as correct--->(A)
BaseOperationRequest[] baseOperationRequestArray = new ObjectMapper().readValue(object, BaseOperationRequest[].class);//getting exception --->(B)
System.out.println(baseOperationRequestArray);
}
}

现在,我这样调用它:

第一种情况无成员(member) map 通话:

<server>:<port>/.../process/[{"operationId":1,"command":"ZADD","gameId":"t5","key":"abc"}]

正在调用process方法,并且由于Jackson被告知在命令ZADD时创建ZAddBaseOperationRequest的对象,因此它正在执行但 command 本身的值在结果对象中被指定为 null

请解释一下为什么? command 的值到哪里去了?

第二种情况与成员(member)通话 map : :/.../process/[{"members":{"a":1.0},"operationId":1,"command":"ZADD","gameId":"t5","key":"abc “}]

那么在这种情况下,等式 (A) 显示[{"members":{"a":1.0,b 就是这样,GET 的其他部分去了哪里。

这让我很生气。 :)。提前致谢..

请帮忙。

最佳答案

It is not a good practice to send json as path parameter.

要解决您的问题,请在 JsonTypeInfo 注释中添加 visible=true 。您的声明将变为:

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "command",
visible = true
)

根据 visible 的 jackson 文档:

Property that defines whether type identifier value will be passed as part of JSON stream to deserializer (true), or handled and removed by TypeDeserializer (false). Default value is false, meaning that Jackson handles and removes the type identifier from JSON content that is passed to JsonDeserializer.

关于java - Jackson 解析中对象值为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29943072/

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