admin管理员组文章数量:1320616
A webservice call, which is out of my control, returns a json response in this format:
[1737189665,1.0001,2.1123,"some string"]
The json consists of the bare values, i.e. without any property names. I know the property names (timestamp, min, max, message) from the documentation of the webservice.
That json must be mapped into an object of type Result
@Data // lombok
@Builder // lombok
public class Result {
Long timestamp;
Double min;
Double max;
String message;
}
What is the best way to do the mapping with the jackson library? Why jackson? Because my application has already chosen jackson as library to handle json.
I have already a working solution with a custom deserializer, but I am not sure if this is really the best way. Is the CustomDeserializer really necessary?
My solution is to register a custom deserializer with the Result class:
@Data
@Builder
@JsonDeserialize(using = ResultDeserializer.class)
public class Result {
// ...
}
The ResultDeserializer looks like this:
public class ResultDeserializer extends StdDeserializer<Result> {
// serialVersionId and constructors omitted
@Override
public Result deserialize(JsonParser p, DeserializationContext ctx) throws IOException, JacksonException {
JsonNode node = p.getCodec().readTree(p);
Iterator<JsonNode> children = node.elements();
return Result.builder()
.timestamp(children.next().asLong();)
.min(children.next().asDouble())
.max(children.next().asDouble())
.message(children.next().asText())
.build();
}
}
The mapping looks like this:
Object[] rawJson = "[1737189665,1.0001,2.1123,\"some string\"]"; // in reality retrieved from webservice
ObjectMapper mapper = new ObjectMapper();
Result result = mapper.convertValue(rawJson, Result.class);
本文标签: How to deserialize json without property names with jackson libraryStack Overflow
版权声明:本文标题:How to deserialize json without property names with jackson library? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742077804a2419511.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论