[英]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"}]
}
它結合了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保持完整。
嘗試使用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.