如何序列化json以Map?

ukdjmx9f  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(453)

我需要序列化json以Map。我儿子长得像这样:

{
   items: [{
      "name": "Test1",
      "value": {
         "id": 1,
         "count": 5
      }
   }]
}

我有以下课程:

public class Value {
    public int id;
    public int count;
}
public class ItemManager {
    public Map<String, Value> items;
}

我试着这样反序列化它:

class Main {
    public static void main(String... args) {
        ObjectMapper mapper = new ObjectMapper();
        ItemManager manager = mapper.read(args[0], ItemManager.class);
    }
}

但我有以下例外:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `test.ItemManager` out of START_ARRAY token
 at [Source: (String)"{

我需要把 name 作为一把钥匙 value 作为一种价值。有人能帮忙吗?

iklwldmw

iklwldmw1#

这里有一个简单的自定义反序列化程序,可以执行您想要的操作(我使用了jackson v2.12.4 ) :

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;

public class ItemManagerDeserializer extends StdDeserializer<ItemManager> {

    public ItemManagerDeserializer() {
        this(null);
    }

    public ItemManagerDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public ItemManager deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        JsonNode node = jp.getCodec().readTree(jp);
        ObjectCodec mapper = jp.getCodec();

        ItemManager itemManager = new ItemManager();
        for (JsonNode element : node.get("items")) {
            String key = element.get("name").asText();
            ItemManager.Value value = mapper.treeToValue(element.get("value"), ItemManager.Value.class);
            itemManager.getItems().put(key, value);
        }

        return itemManager;
    }
}

我已经创建了一个静态 Value 课堂 ItemManager 类并示例化 items 构造函数中的属性( new HashMap<>() ).
然后,您可以注册并使用此反序列化程序,如下所示:

public static void main(String[] args) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(ItemManager.class, new ItemManagerDeserializer());
    mapper.registerModule(module);

    ItemManager itemManager = mapper.readValue(args[0], ItemManager.class);
    itemManager.getItems().forEach((key, value) -> System.out.println("key: " + key + ", value: " + value));
}

相关问题