gpt4 book ai didi

json - 如何解析 json 但将一个特定节点序列化为字符串?

转载 作者:行者123 更新时间:2023-12-02 01:08:49 25 4
gpt4 key购买 nike

假设我有这个 JSON 示例:

{
"title" : "tttt",
"custom" : {
"a" : "aaaaa",
"b" : "bbbbb",
"c" : {
"d" : "dddd"
}
}
}

我想将其反序列化为以下类:

public class Article {
private String title;
private String custom;

public void setTitle(String title) { this.title = title; }
public String getTitle() { return title; }
public void setCustom(String custom) { this.custom = custom; }
public String getCustom() { return custom; }
}

我想要的结果是标题按正常方式反序列化,但“自定义”下的 json 子树不反序列化并设置为原始 json 字符串:

ObjectMapper mapper = new ObjectMapper();
Article article = mapper.readValue(content, Article.class);
assertEquals(article.getTitle(), "tttt");
assertEquals(article.getCustom(),
"{\"a\" : \"aaaaa\"," +
"\"b\" : \"bbbbb\"," +
"\"c\" : {" +
"\"d\" : \"dddd\" " +
"}" +
"}");

另一个重要注意事项是,我无法将自定义节点下的原始 JSON 更改为使用转义 json,因此它将被视为字符串。

最佳答案

我发现了一种更简单的方法。你可以只添加到你的 dto 下一个 setter :

public void setCustom(JsonNode custom) { this.custom = custom.toString(); }

为了得到简单的字符串,用 @JsonRawValue 注释它

关于json - 如何解析 json 但将一个特定节点序列化为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19438833/

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