将HashMap序列化为JSON字符串,同时避免使用Java中的某些字段 [英] Serialize HashMap to a JSON string while avoiding certain fields in Java
问题描述
我有如下地图:
Map map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
我需要将此地图转换为JSON字符串。我知道这可以使用Jackson完成,如下所示:
I need to convert this map into a JSON string. I know that this can be done using Jackson as below:
new ObjectMapper().writeValueAsString(map);
问题是,我不想映射 key3
到字符串。输出字符串应如下所示:
The problem is, I do not want to map key3
to the String. The output String should be as below:
{"key1":"value1","key2":"value2"}
在将序列化为字符串时,有什么方法可以避免HashMap中的某些字段?此外,我想在序列化时向String添加某些字段。例如,我需要添加一个名为key4的字段,其值为value4。因此,最终字符串应为:
Is there any way to avoid certain fields from the HashMap while serializing it to a String? Moreover, I want to add certain fields to the String while serializing. For instance, I need to add a field called "key4" with a value "value4". Thus, the final String should be:
{"key1":"value1","key2":"value2","key4":"value4"}
我如何使用杰克逊这样做?或者在Java中还有其他方法吗?
How do I do this using Jackson? Or is there any other way to do this in Java?
推荐答案
如果要序列化 HashMap
像这样,您应该实现自定义序列化程序。下面是一个示例:
If you want to serialize a HashMap
like this, you should implement a custom serializer. Here is one example:
public class CustomSerializer extends StdSerializer<Map> {
protected CustomSerializer() {
super(Map.class);
}
@Override
public void serialize(Map map, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
jsonGenerator.writeStartObject();
for (Object key : map.keySet()) {
if(!"key3".equals(key)){
jsonGenerator.writeStringField((String) key, (String) map.get(key));
}
}
jsonGenerator.writeStringField("key4","value4");
jsonGenerator.writeEndObject();
}
}
public class Main {
public static void main(String[] args) throws Exception{
Map<String, String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
map.put("key3","value3");
ObjectMapper mapper = new ObjectMapper();
SimpleModule serializerModule = new SimpleModule("SerializerModule", new Version(1, 0, 0, null, "mt", "customSerializerTest"));
serializerModule.addSerializer(new CustomSerializer());
mapper.registerModule(serializerModule);
System.out.println(mapper.writeValueAsString(map));
}
}
Output:
{"key1":"value1","key2":"value2","key4":"value4"}
这篇关于将HashMap序列化为JSON字符串,同时避免使用Java中的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!