繁体   English   中英

如何将HashMap作为ArrayList序列化为JSON?

[英]How to serialize HashMap as ArrayList as JSON?

我有一个具有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 ,但是get can not start an object expecting field name错误can not start an object expecting field name

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"}]
}

它结合了JacksonObjectNode类和一些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保持完整。

尝试使用keySet和values方法,该方法返回键和值的集合,然后使用类似以下内容的方法转换为arraylist:

List<String> keyList = new ArrayList<>(attrMap.keySet());
List<String> valueList = new ArrayList<>(attrMap.values());

要非常具体地回答您的问题,您需要执行以下操作:

final Map<String, String>     attrMap     = new HashMap<String, String>();
attrMap.put("name", "value of name");
attrMap.put("content", "value of content");
List<String> keyList = new ArrayList<>(attrMap.size());
for (Map.Entry<String, String> entry : attrMap.entrySet()) {//iterate over map
  keyList.add("{" + entry.getKey() + ": \"" + entry.getValue() + "\"}");//add key followed by value
}
System.out.println(keyList);

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

除了注释:由于地图中没有添加方法,因此您的信息似乎有错字。 希望你的意思是放而不加。 也有实用程序,如Gson,jackson等可用于转换为json对象。

如果您不介意手动执行此操作,请采用以下代码(未经测试,但应该可以运行):

ArrayList<String> entries = new ArrayList<>(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());

这可能是最简单的方法,因为如果您想使用JSON库,则必须修改输出(不建议这样做,因为它强加了可维护性),或者为HashMap编写自定义序列化器/反序列化器,这将是更复杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM