将JSON对象转换为一组自定义对象

tct7dpnv  于 2023-10-21  发布在  其他
关注(0)|答案(1)|浏览(128)

我有一个类似下面的json对象。

{
  "key1": {
    "code1": "name1",
    "code2": "name2",
    ...
  },
  "key2": {
    "code1": "name1",
    "code2": "name2",
    ...
  },
  ...
}

我想把这个json对象转换成Map<String,Set< Key >>而不是Map<String,Map<String,String>>,我可以用ObjectMapper正常完成。
我想要的Key类看起来与此类似。

public class Key{
  private String code;
  private String Name;
}

我在chatgpt的帮助下尝试了一些自定义编译器。

public static class KeyListDeserializer extends JsonDeserializer<Set<Key>> {

    @Override
    public Set<Key> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        Set<Key> keyList = new HashSet<>();
        JsonNode rootNode = jp.getCodec().readTree(jp);

        Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
        while (fields.hasNext()) {
            Map.Entry<String, JsonNode> field = fields.next();
            String code = field.getKey();
            String name = field.getValue().asText();

            Key key = new Key();
            key.setCode(code);
            key.setName(name);

            keyList.add(key);
        }

        return keyList;
    }
}

但它不工作,抛出下面的错误:

Exception in thread "main" com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.util.HashSet<um.Test1$Key>` from Object value (token `JsonToken.START_OBJECT`)

我可以将它转换为Map<String,Map>,并手动将其转换为Map<String,Set< Key >>,但我认为最好通过objectmapper本身来实现,而不是单独处理。
如何将对象直接转换为Set?

yruzcnhs

yruzcnhs1#

要使用Jackson的ObjectMapper将JSON对象直接转换为Map<String, Set<Key>>,可以为Key类创建自定义转换器,并配置ObjectMapper,使其在转换JSON对象时使用此自定义转换器。你可以这样做:
首先,让我们用适当的getter和setter定义Key类:

public class Key {
    private String code;
    private String name;

    // Constructors, getters, setters, and any other methods
}

接下来,为Key类创建一个自定义解析器:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;

public class KeyDeserializer extends JsonDeserializer<Key> {
    @Override
    public Key deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        String code = node.fieldNames().next();
        String name = node.get(code).asText();
        return new Key(code, name);
    }
}

现在,配置您的ObjectMapper以使用自定义解析器:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class Main {
    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        // Register the custom deserializer for the Key class
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Key.class, new KeyDeserializer());
        objectMapper.registerModule(module);

        String json = "YOUR_JSON_STRING_HERE"; // Replace with your JSON data

        // Deserialize the JSON into a Map<String, Set<Key>>
        Map<String, Set<Key>> map = objectMapper.readValue(json, new TypeReference<Map<String, Set<Key>>>() {});

        // Now you have the desired Map<String, Set<Key>>
    }
}

"YOUR_JSON_STRING_HERE"替换为实际的JSON数据。这段代码应该使用Key类的自定义转换器将JSON对象正确转换为Map<String, Set<Key>>

相关问题