如何序列化具有一个json字符串成员的Java对象
我有一个Pojo,其中包含一个成员如何序列化具有一个json字符串成员的Java对象,java,json,jackson,Java,Json,Jackson,我有一个Pojo,其中包含一个成员displayPropsJson,这是客户端json字符串。在存储到服务器上之前,将使用JSON模式对其进行验证。 i、 e 我希望此文件的序列化版本将displayPropsJson作为displayProps子对象输出,例如: { "id" :23, "name: : "itemsName", "displayProps" : { "bold" : true, "htmlAllowed" : true,
displayPropsJson
,这是客户端json字符串。在存储到服务器上之前,将使用JSON模式对其进行验证。
i、 e
我希望此文件的序列化版本将displayPropsJson作为displayProps子对象输出,例如:
{
"id" :23,
"name: : "itemsName",
"displayProps" : {
"bold" : true,
"htmlAllowed" : true,
"icon" : "star.jpg"
}
}
如何使用输出元素和json字符串作为json的Jackson序列化程序来实现这一点?
displayPropsJson将有所不同,但始终是有效的json。是的,我确信这可以通过自定义Jackson序列化程序完成。您可以做的另一件事是实现JsonSerializable, } 另一种可能性是实施
最后一种可能是切换库和使用,这使得很容易将对象序列化到JSON之外。
除了创建自定义序列化器之外,您还可以考虑两个选项。p>
- 使用
注释标记 应按原样序列化,而不引用字符@JsonRawString
- 在对象实例()中使用
,并提供一个getter方法,该方法从json字符串值反序列化返回ObjectMapper
JsonNode
public class JacksonRawString {
public static class Item {
final private ObjectMapper mapper;
public Long id = 23l;
public String name = "itemsName";
@JsonRawValue
public String displayPropsJson = "{\"bold\" : true, \"htmlAllowed\" : true, " +
"\"icon\" :\"star.jpg\" }";
public JsonNode getDisplayPropsJson2() throws IOException {
return mapper.readTree(displayPropsJson);
}
public Item(ObjectMapper mapper) {
this.mapper = mapper;
}
}
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
System.out.println(
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Item(mapper)));
}
}
输出:
{
"id" : 23,
"name" : "itemsName",
"displayPropsJson" : {"bold" : true, "htmlAllowed" : true, "icon" :"star.jpg" },
"displayPropsJson2" : {
"bold" : true,
"htmlAllowed" : true,
"icon" : "star.jpg"
}
}
请注意,
displayPropsJson2
获得了漂亮的输出,因为它被序列化为JsonNode
,这是一个有趣的输出。当然,您可以使用jackson序列化程序并将displayProps的值打印为json,但我很好奇反序列化程序是否能够处理它。你能用你的发现更新这个问题吗?构建JSON树,然后编辑以用它的树替换displayPropsJson。然后序列化。谢谢Alexey,我使用了@JsonRawString。实现上的一个额外约束是,对象还需要可序列化才能持久化。JsonNode类本身不可序列化。我是否可以使用其他注释来支持此输入/输出。@claya只要将ObjectMapper字段标记为“transient”,您就应该能够使Item类可序列化。如果类中没有这样的字段,为什么JsonNode需要可序列化?
{
"id" : 23,
"name" : "itemsName",
"displayPropsJson" : {"bold" : true, "htmlAllowed" : true, "icon" :"star.jpg" },
"displayPropsJson2" : {
"bold" : true,
"htmlAllowed" : true,
"icon" : "star.jpg"
}
}