gpt4 book ai didi

java - 如何在 Java 中反序列化 JSON 对象数组

转载 作者:行者123 更新时间:2023-11-30 01:45:37 25 4
gpt4 key购买 nike

所以我习惯从给定的 API/端点获取 JSON 对象,例如:

{
"count": 5,
"results": [
{
"example": "test",
"is_valid": true
},
{
"example": "test2",
"is_valid": true
}
]
}

在扩展 com.fasterxml.jackson.databind.deser.std.StdDeserializer 的自定义反序列化器中,我知道我可以像这样使用 JsonParser 对象来让基本节点工作,即:

@Override
public ResultExample deserialize(JsonParser jp, DeserializationContext ctxt) {
JsonNode node = jp.getCodec().readTree(jp);
JsonNode count = node.get("count");
// code to put parsed objects into a ResultExample object...
}

但是,我刚刚遇到了一个仅返回 JSON 对象数组的 API,例如:

[
{
"example": "test",
"is_valid": true
},
{
"example": "test2",
"is_valid": true
},
]

所以,我不相信我可以像以前一样解析它。使用 Jackson 解析此内容的正确方法是什么?

最佳答案

这可能对您有帮助:

import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();

String json = "[\r\n" + " {\r\n" + " \"example\": \"test\",\r\n" + " \"is_valid\": true\r\n"
+ " },\r\n" + " {\r\n" + " \"example\": \"test2\",\r\n" + " \"is_valid\": true\r\n"
+ " }\r\n" + "]";
Example[] ex = mapper.readValue(json, Example[].class);

}

}

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "example", "is_valid" })
class Example {

@JsonProperty("example")
private String example;
@JsonProperty("is_valid")
private Boolean isValid;

public String getExample() {
return example;
}

@JsonProperty("example")
public void setExample(String example) {
this.example = example;
}

@JsonProperty("is_valid")
public Boolean getIsValid() {
return isValid;
}

@JsonProperty("is_valid")
public void setIsValid(Boolean isValid) {
this.isValid = isValid;
}
}

关于java - 如何在 Java 中反序列化 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123314/

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