gpt4 book ai didi

java - 如何将 HashMap 序列化为 ArrayList 为 JSON?

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:09 24 4
gpt4 key购买 nike

我有一个具有 HashMap 的模型,如下所示:

private Map<String, String>     attrMap     = new HashMap<String, String>();

并像这样初始化它:

attrMap.add("name", "value of name");
attrMap.add("content", "value of content");

但我想将此字段序列化为对象的ArrayList,如下所示:

[{name: "value of name"}, {content: "value of content"}]

更新1

有没有办法在序列化过程中调用函数,如下所示:

@JsonSerializer(serializeAttrMap)
private Map<String, String> attrMap = new HashMap<String, String>();

public String serializeAttrMap() {
ArrayList<String> entries = new ArrayList<>(this.attrMap.size());
for(Map.Entry<String,String> entry : attrMap.entrySet())
entries.add(String.format("{%s: \"%s\"}",
entry.getKey(), entry.getValue()));
return Arrays.toString(entries.toArray());
}

更新2

我使用此类来序列化attrMap,但出现无法启动期望字段名称的对象错误。

import java.io.IOException;
import java.util.Map;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

public class AttrMapSerializer extends JsonSerializer<Map<String, String>> {

@Override
public void serialize(Map<String, String> attributes, JsonGenerator generator, SerializerProvider provider) throws IOException, JsonProcessingException {
for (Map.Entry<String, String> attribute : attributes.entrySet())
{
generator.writeStartObject();
generator.writeObjectField("name", attribute.getKey());
generator.writeObjectField("content", attribute.getValue());
generator.writeEndObject();
}
}
}

我是 Jackson 的初学者

最佳答案

以下构造将创建所需的输出:

@Test
public void testJackson() throws JsonProcessingException {
// Declare the map
Map<String, String> attrMap = new HashMap<>();

// Put the data in the map
attrMap.put("name", "value of name");
attrMap.put("content", "value of content");

// Use an object mapper
final ObjectMapper objectMapper = new ObjectMapper();

// Collect to a new object structure
final List<ObjectNode> collected = attrMap.entrySet()
.stream()
.map(entry -> objectMapper.createObjectNode().put(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());

// The output
final String json = objectMapper.writeValueAsString(collected);

System.out.println(json); // -> [{"name":"value of name"},{"content":"value of content"}]
}

它结合使用 Jackson 中的 ObjectNode 类和一些 Java 8 流来收集新数据。

编辑:在OP提供更多信息后,他们要求另一种方法,我添加了这个替代方案。

另一种方法是简单地在属性上使用@JacksonSerializer

// This is the serializer
public static class AttrMapSerializer extends JsonSerializer<Map<String, String>> {
@Override
public void serialize(
final Map<String, String> value,
final JsonGenerator jgen, final SerializerProvider provider) throws IOException {

// Iterate the map entries and write them as fields
for (Map.Entry<String, String> entry : value.entrySet()) {
jgen.writeStartObject();
jgen.writeObjectField(entry.getKey(), entry.getValue());
jgen.writeEndObject();
}
}
}

// This could be the POJO
public static class PojoWithMap {
private Map<String, String> attrMap = new HashMap<>();

// This instructs the ObjectMapper to use the specified serializer
@JsonSerialize(using = AttrMapSerializer.class)
public Map<String, String> getAttributes() {
return attrMap;
}
}

public static void main(String... args) throws JsonProcessingException {
final PojoWithMap pojoWithMap = new PojoWithMap();
pojoWithMap.getAttributes().put("name", "value of name");
pojoWithMap.getAttributes().put("content", "value of content");


final String json = new ObjectMapper().writeValueAsString(pojoWithMap);
System.out.println(json); // ->
}

这样,序列化就被外部化为序列化器,并且 POJO 完好无损。

关于java - 如何将 HashMap 序列化为 ArrayList 为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27666963/

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