java - Serialize flat object to nested JSON structure
问题描述
Challenge
I have a completely flat (POGO/POJO) object which I need to serialize into a nested JSON structure. Preferably using Jackson annotations and/or a custom Serializer
I'm only interested in serializing from object to JSON, deserializing is not needed.
Example
I would like to turn this class:
class SomeClass {
@JsonProperty('Business.Name')
BigDecimal prop1 = 42.0
@JsonProperty('Other.Nested.Business.Name')
BigDecimal prop2 = 3.14
}
Into this JSON:
{
"Other" : {
"Nested.Business.Name" : 3.14
},
"Business.Name" : 42.0
}
Catch 22
The code for the class is auto-generated. I have some influence over the generation, but it needs to be completely flat!
Any help would be much appreciated!
Additional info
I already tried making a custom serializer, but failed to write the nested structure.
class SomeClassSerializer extends StdSerializer<SomeClass> {
void serialize(SomeClass value, JsonGenerator jgen, SerializerProvider provider) {
jgen.writeStartObject()
jgen.writeNumberField("Business.Name", value.prop1)
//how to write the nested structure
jgen.writeEndObject()
}
....
}
解决方案
Where it says // how to write the nested structure, have you tried something like
jgen.writeObjectFieldStart("Other")
jgen.writeNumberField("Nested.BusinessName", value.prop2)
jgen.writeEndObject()
推荐阅读
- javascript - 如何防止抽屉菜单内的内容缩小?
- javascript - JS - 创建一个回调函数,该函数接受调用它的函数返回的对象
- github - 无法将参考推送到远程。尝试先运行“拉”以集成您的更改
- r - R - ggplot geom_smooth 限制 y 轴而不改变回归线
- node.js - 如何使用 nodejs 下载带有 Blob url 的视频
- angular - 无法将输入参数发送到 Angular 中的验证器指令
- android - 如何在android的build.gradle文件中定义flutter应用程序的基本URL?
- reactjs - 你能帮我转换这个 React 星级吗?
- ios - 尝试 FCM。第一步
- javascript - vue.js 3 单文件组件在script标签中的调用方法