如何通过Jackson将类属性序列化为JSON节点而非JSON属性?
解决方案
首先要明确:你给出的目标JSON格式不符合JSON语法规范——JSON对象必须由键值对组成,不能直接将数组/对象作为对象的元素而无对应键。推测你实际需求是将原对象的两个属性值直接作为顶级JSON数组的元素,合法格式如下:
[ [ { "name":"John", "age" : "35" } ], { "weight" : "70" } ]
如果是这个需求,完全可以通过为Info类编写自定义Jackson序列化器实现,不需要使用ObjectNode,也无需修改集合或Person类的序列化逻辑:
1. 编写自定义序列化器
import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class InfoSerializer extends JsonSerializer<Info> { @Override public void serialize(Info info, JsonGenerator gen, SerializerProvider serializers) throws IOException { // 开启顶级数组 gen.writeStartArray(); // 直接序列化personList作为数组第一个元素 serializers.defaultSerializeValue(info.getPersonList(), gen); // 直接序列化personProperties作为数组第二个元素 serializers.defaultSerializeValue(info.getPersonProperties(), gen); gen.writeEndArray(); } }
2. 给Info类绑定序列化器
修改Info类,添加@JsonSerialize注解指定自定义序列化器,同时修正你代码里构造方法名与类名不一致的问题:
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import java.util.List; import java.util.Map; @JsonSerialize(using = InfoSerializer.class) public class Info { private final List<Person> personList; private final Map<String, String> personProperties; public List<Person> getPersonList() { return List.copyOf(personList); } public Map<String, String> getPersonProperties() { return Map.copyOf(personProperties); } @JsonCreator // 构造方法名需与类名一致,原代码写成PrintChequeInfo,此处修正 public Info( @JsonProperty("personList") List<Person> personList, @JsonProperty("personProperties") Map<String, String> personProperties) { this.personList = personList; this.personProperties = personProperties; } }
3. 序列化测试
使用ObjectMapper序列化时,就会生成符合要求的格式:
ObjectMapper mapper = new ObjectMapper(); List<Person> persons = List.of(new Person("John", "35")); Map<String, String> props = Map.of("weight", "70"); Info info = new Info(persons, props); String json = mapper.writeValueAsString(info); // 输出结果即为上述合法的数组格式
注意:如果坚持要生成你给出的无效JSON格式,Jackson无法实现——它会严格遵循JSON语法规范,这种无效格式也无法被标准JSON解析器解析,不适合HTTP传输场景。
内容的提问来源于stack exchange,提问作者Oblivion
相关产品推荐
相关产品推荐

