Java Jackson找不到路径的(映射)密钥反序列化器?

Java Jackson找不到路径的(映射)密钥反序列化器?,java,json,jackson,jackson-databind,Java,Json,Jackson,Jackson Databind,我有一个奇怪的问题,我有一个HashMap,我将其序列化以供以后在磁盘上使用 它是一个HashMapConverterMetadata自定义类,我编写该类是为了跟踪音乐文件元数据 ConverterMetadata似乎有正确的标记,在我的测试中,我已经确认Jackson可以写入和读取Map实例,所以我不完全确定这里发生了什么,以及为什么它说它在key(Path)对象上断开 以下是异常、类、输出的JSON以及读取/写入它的方法: 例外情况: Exception in thread "main" c

我有一个奇怪的问题,我有一个HashMap,我将其序列化以供以后在磁盘上使用

它是一个
HashMap
ConverterMetadata自定义类,我编写该类是为了跟踪音乐文件元数据

ConverterMetadata似乎有正确的标记,在我的测试中,我已经确认Jackson可以写入和读取
Map
实例,所以我不完全确定这里发生了什么,以及为什么它说它在key(Path)对象上断开

以下是异常、类、输出的JSON以及读取/写入它的方法:

例外情况:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class java.nio.file.Path]
 at [Source: (File); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:599)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findKeyDeserializer(DeserializerCache.java:168)
    at com.fasterxml.jackson.databind.DeserializationContext.findKeyDeserializer(DeserializationContext.java:500)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.createContextual(MapDeserializer.java:248)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:682)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:482)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4191)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4010)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge(SpaceBridge.java:151)
    at com.protonmail.sarahszabo.stellar.StellarMode$2.start(StellarMode.java:87)
    at com.protonmail.sarahszabo.stellar.Main.stellarConversion(Main.java:203)
    at com.protonmail.sarahszabo.stellar.Main.main(Main.java:77)
/**
 * A representation of .opus metadata. Used in concordance with a
 * {@link StellarOPUSConverter}. All fields are immutable.
 */
public final class ConverterMetadata {

    /**
     * The default metadata instance.
     */
    public static final ConverterMetadata DEFAULT_METADATA = new ConverterMetadata("Unknown Artist",
            "Unknown Title", Main.FULL_PROGRAM_NAME, LocalDate.MAX, StellarGravitonField.newPath(""), Integer.MAX_VALUE);

    @JsonProperty
    private final String artist;
    @JsonProperty
    private final String title;
    @JsonProperty
    private final String createdBy;
    @JsonProperty
    private final LocalDate stellarIndexDate;
    @JsonProperty
    private final Path albumArtPath;
    @JsonProperty
    private final int bitrate;

    /**
     * Constructs a new {@link ConverterMetadata} with the specified arguments.
     *
     *
     * @param artist The artist for this track
     * @param title The title of this track
     * @param createdBy The program that created this track/last modified this
     * track
     * @param date The date this track was created
     * @param albumArtPath The path to the album art
     * @param bitrate The bitrate of the track
     */
    @JsonCreator
    public ConverterMetadata(@JsonProperty(value = "artist") String artist,
            @JsonProperty(value = "title") String title, @JsonProperty(value = "createdBy") String createdBy,
            @JsonProperty(value = "stellarIndexDate") LocalDate date, @JsonProperty(value = "albumArtPath") Path albumArtPath,
            @JsonProperty(value = "bitrate") int bitrate) {
        //Do Consructor Stuff Here
    }
}
Map<Path, ConverterMetadata> LIBRARY_LEDGER = new HashMap<>();
//Earlier in the code, write ledger, to disk
MAPPER.writeValue(LIBRARY_LEDGER_PATH.toFile(), LIBRARY_LEDGER);
//Later we read the ledger    
Map<Path, ConverterMetadata> previousLedger = MAPPER.readValue(LIBRARY_LEDGER_PATH.toFile(),
                        new TypeReference<HashMap<Path, ConverterMetadata>>() {
                });
                LIBRARY_LEDGER.putAll(previousLedger);
{"/home/sarah/Music/Indexing/Playlists/Best Playlist/Spiral.opus":{"artist":"Vangelis","title":"Spiral","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,7,23],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Spiral.png","bitrate":320},"/home/sarah/Music/Indexing/Playlists/Finished/Aphelion.opus":{"artist":"Scandroid","title":"Aphelion","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,8,8],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Aphelion.png","bitrate":320}
    <properties>
  ...
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.9.8</jackson.version>
  ...
</properties>

<dependencies>
  ...
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
</dependencies>
转换器元数据类:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class java.nio.file.Path]
 at [Source: (File); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:599)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findKeyDeserializer(DeserializerCache.java:168)
    at com.fasterxml.jackson.databind.DeserializationContext.findKeyDeserializer(DeserializationContext.java:500)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.createContextual(MapDeserializer.java:248)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:682)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:482)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4191)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4010)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge(SpaceBridge.java:151)
    at com.protonmail.sarahszabo.stellar.StellarMode$2.start(StellarMode.java:87)
    at com.protonmail.sarahszabo.stellar.Main.stellarConversion(Main.java:203)
    at com.protonmail.sarahszabo.stellar.Main.main(Main.java:77)
/**
 * A representation of .opus metadata. Used in concordance with a
 * {@link StellarOPUSConverter}. All fields are immutable.
 */
public final class ConverterMetadata {

    /**
     * The default metadata instance.
     */
    public static final ConverterMetadata DEFAULT_METADATA = new ConverterMetadata("Unknown Artist",
            "Unknown Title", Main.FULL_PROGRAM_NAME, LocalDate.MAX, StellarGravitonField.newPath(""), Integer.MAX_VALUE);

    @JsonProperty
    private final String artist;
    @JsonProperty
    private final String title;
    @JsonProperty
    private final String createdBy;
    @JsonProperty
    private final LocalDate stellarIndexDate;
    @JsonProperty
    private final Path albumArtPath;
    @JsonProperty
    private final int bitrate;

    /**
     * Constructs a new {@link ConverterMetadata} with the specified arguments.
     *
     *
     * @param artist The artist for this track
     * @param title The title of this track
     * @param createdBy The program that created this track/last modified this
     * track
     * @param date The date this track was created
     * @param albumArtPath The path to the album art
     * @param bitrate The bitrate of the track
     */
    @JsonCreator
    public ConverterMetadata(@JsonProperty(value = "artist") String artist,
            @JsonProperty(value = "title") String title, @JsonProperty(value = "createdBy") String createdBy,
            @JsonProperty(value = "stellarIndexDate") LocalDate date, @JsonProperty(value = "albumArtPath") Path albumArtPath,
            @JsonProperty(value = "bitrate") int bitrate) {
        //Do Consructor Stuff Here
    }
}
Map<Path, ConverterMetadata> LIBRARY_LEDGER = new HashMap<>();
//Earlier in the code, write ledger, to disk
MAPPER.writeValue(LIBRARY_LEDGER_PATH.toFile(), LIBRARY_LEDGER);
//Later we read the ledger    
Map<Path, ConverterMetadata> previousLedger = MAPPER.readValue(LIBRARY_LEDGER_PATH.toFile(),
                        new TypeReference<HashMap<Path, ConverterMetadata>>() {
                });
                LIBRARY_LEDGER.putAll(previousLedger);
{"/home/sarah/Music/Indexing/Playlists/Best Playlist/Spiral.opus":{"artist":"Vangelis","title":"Spiral","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,7,23],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Spiral.png","bitrate":320},"/home/sarah/Music/Indexing/Playlists/Finished/Aphelion.opus":{"artist":"Scandroid","title":"Aphelion","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,8,8],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Aphelion.png","bitrate":320}
    <properties>
  ...
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.9.8</jackson.version>
  ...
</properties>

<dependencies>
  ...
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
</dependencies>
从分类帐文件AKA initBridge()写入/读取的代码:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class java.nio.file.Path]
 at [Source: (File); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:599)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findKeyDeserializer(DeserializerCache.java:168)
    at com.fasterxml.jackson.databind.DeserializationContext.findKeyDeserializer(DeserializationContext.java:500)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.createContextual(MapDeserializer.java:248)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:682)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:482)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4191)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4010)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge(SpaceBridge.java:151)
    at com.protonmail.sarahszabo.stellar.StellarMode$2.start(StellarMode.java:87)
    at com.protonmail.sarahszabo.stellar.Main.stellarConversion(Main.java:203)
    at com.protonmail.sarahszabo.stellar.Main.main(Main.java:77)
/**
 * A representation of .opus metadata. Used in concordance with a
 * {@link StellarOPUSConverter}. All fields are immutable.
 */
public final class ConverterMetadata {

    /**
     * The default metadata instance.
     */
    public static final ConverterMetadata DEFAULT_METADATA = new ConverterMetadata("Unknown Artist",
            "Unknown Title", Main.FULL_PROGRAM_NAME, LocalDate.MAX, StellarGravitonField.newPath(""), Integer.MAX_VALUE);

    @JsonProperty
    private final String artist;
    @JsonProperty
    private final String title;
    @JsonProperty
    private final String createdBy;
    @JsonProperty
    private final LocalDate stellarIndexDate;
    @JsonProperty
    private final Path albumArtPath;
    @JsonProperty
    private final int bitrate;

    /**
     * Constructs a new {@link ConverterMetadata} with the specified arguments.
     *
     *
     * @param artist The artist for this track
     * @param title The title of this track
     * @param createdBy The program that created this track/last modified this
     * track
     * @param date The date this track was created
     * @param albumArtPath The path to the album art
     * @param bitrate The bitrate of the track
     */
    @JsonCreator
    public ConverterMetadata(@JsonProperty(value = "artist") String artist,
            @JsonProperty(value = "title") String title, @JsonProperty(value = "createdBy") String createdBy,
            @JsonProperty(value = "stellarIndexDate") LocalDate date, @JsonProperty(value = "albumArtPath") Path albumArtPath,
            @JsonProperty(value = "bitrate") int bitrate) {
        //Do Consructor Stuff Here
    }
}
Map<Path, ConverterMetadata> LIBRARY_LEDGER = new HashMap<>();
//Earlier in the code, write ledger, to disk
MAPPER.writeValue(LIBRARY_LEDGER_PATH.toFile(), LIBRARY_LEDGER);
//Later we read the ledger    
Map<Path, ConverterMetadata> previousLedger = MAPPER.readValue(LIBRARY_LEDGER_PATH.toFile(),
                        new TypeReference<HashMap<Path, ConverterMetadata>>() {
                });
                LIBRARY_LEDGER.putAll(previousLedger);
{"/home/sarah/Music/Indexing/Playlists/Best Playlist/Spiral.opus":{"artist":"Vangelis","title":"Spiral","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,7,23],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Spiral.png","bitrate":320},"/home/sarah/Music/Indexing/Playlists/Finished/Aphelion.opus":{"artist":"Scandroid","title":"Aphelion","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,8,8],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Aphelion.png","bitrate":320}
    <properties>
  ...
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.9.8</jackson.version>
  ...
</properties>

<dependencies>
  ...
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
</dependencies>
POM:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot find a (Map) Key deserializer for type [simple type, class java.nio.file.Path]
 at [Source: (File); line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1452)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._handleUnknownKeyDeserializer(DeserializerCache.java:599)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findKeyDeserializer(DeserializerCache.java:168)
    at com.fasterxml.jackson.databind.DeserializationContext.findKeyDeserializer(DeserializationContext.java:500)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.createContextual(MapDeserializer.java:248)
    at com.fasterxml.jackson.databind.DeserializationContext.handleSecondaryContextualization(DeserializationContext.java:682)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:482)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4191)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4010)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2922)
    at com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge(SpaceBridge.java:151)
    at com.protonmail.sarahszabo.stellar.StellarMode$2.start(StellarMode.java:87)
    at com.protonmail.sarahszabo.stellar.Main.stellarConversion(Main.java:203)
    at com.protonmail.sarahszabo.stellar.Main.main(Main.java:77)
/**
 * A representation of .opus metadata. Used in concordance with a
 * {@link StellarOPUSConverter}. All fields are immutable.
 */
public final class ConverterMetadata {

    /**
     * The default metadata instance.
     */
    public static final ConverterMetadata DEFAULT_METADATA = new ConverterMetadata("Unknown Artist",
            "Unknown Title", Main.FULL_PROGRAM_NAME, LocalDate.MAX, StellarGravitonField.newPath(""), Integer.MAX_VALUE);

    @JsonProperty
    private final String artist;
    @JsonProperty
    private final String title;
    @JsonProperty
    private final String createdBy;
    @JsonProperty
    private final LocalDate stellarIndexDate;
    @JsonProperty
    private final Path albumArtPath;
    @JsonProperty
    private final int bitrate;

    /**
     * Constructs a new {@link ConverterMetadata} with the specified arguments.
     *
     *
     * @param artist The artist for this track
     * @param title The title of this track
     * @param createdBy The program that created this track/last modified this
     * track
     * @param date The date this track was created
     * @param albumArtPath The path to the album art
     * @param bitrate The bitrate of the track
     */
    @JsonCreator
    public ConverterMetadata(@JsonProperty(value = "artist") String artist,
            @JsonProperty(value = "title") String title, @JsonProperty(value = "createdBy") String createdBy,
            @JsonProperty(value = "stellarIndexDate") LocalDate date, @JsonProperty(value = "albumArtPath") Path albumArtPath,
            @JsonProperty(value = "bitrate") int bitrate) {
        //Do Consructor Stuff Here
    }
}
Map<Path, ConverterMetadata> LIBRARY_LEDGER = new HashMap<>();
//Earlier in the code, write ledger, to disk
MAPPER.writeValue(LIBRARY_LEDGER_PATH.toFile(), LIBRARY_LEDGER);
//Later we read the ledger    
Map<Path, ConverterMetadata> previousLedger = MAPPER.readValue(LIBRARY_LEDGER_PATH.toFile(),
                        new TypeReference<HashMap<Path, ConverterMetadata>>() {
                });
                LIBRARY_LEDGER.putAll(previousLedger);
{"/home/sarah/Music/Indexing/Playlists/Best Playlist/Spiral.opus":{"artist":"Vangelis","title":"Spiral","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,7,23],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Spiral.png","bitrate":320},"/home/sarah/Music/Indexing/Playlists/Finished/Aphelion.opus":{"artist":"Scandroid","title":"Aphelion","createdBy":"Stellar OPUS Conversion Library 1.4α","stellarIndexDate":[2018,8,8],"albumArtPath":"file:///tmp/Stellar%20OPUS%20Converter%20Temporary%20Directory15723231348656772389/ReIndexing/Aphelion.png","bitrate":320}
    <properties>
  ...
  <!-- Use the latest version whenever possible. -->
  <jackson.version>2.9.8</jackson.version>
  ...
</properties>

<dependencies>
  ...
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>${jackson.version}</version>
  </dependency>
  ...
</dependencies>

...
2.9.8
...
...
com.fasterxml.jackson.core
杰克逊数据绑定
${jackson.version}
...

您需要为
java.nio.file.Path
类实现密钥反序列化器。它可能如下所示:

class PathKeyDeserializer extends KeyDeserializer {

    @Override
    public Object deserializeKey(String key, DeserializationContext ctxt) {
        return Paths.get(key);
    }
}
您可以注册它并使用,如以下示例所示:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        Map<Path, String> path2String = new HashMap<>();
        path2String.put(Paths.get("user", "downloads"), "Downloads");
        path2String.put(Paths.get("home", "des"), "Desktop");

        SimpleModule nioModule = new SimpleModule();
        nioModule.addKeyDeserializer(Path.class, new PathKeyDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(nioModule);

        String json = mapper.writeValueAsString(path2String);
        System.out.println(json);

        path2String = mapper.readValue(json, new TypeReference<HashMap<Path, String>>() {});
        System.out.println(path2String);
    }

}

您需要为
java.nio.file.Path
类实现密钥反序列化器。它可能如下所示:

class PathKeyDeserializer extends KeyDeserializer {

    @Override
    public Object deserializeKey(String key, DeserializationContext ctxt) {
        return Paths.get(key);
    }
}
您可以注册它并使用,如以下示例所示:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.KeyDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        Map<Path, String> path2String = new HashMap<>();
        path2String.put(Paths.get("user", "downloads"), "Downloads");
        path2String.put(Paths.get("home", "des"), "Desktop");

        SimpleModule nioModule = new SimpleModule();
        nioModule.addKeyDeserializer(Path.class, new PathKeyDeserializer());

        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.registerModule(nioModule);

        String json = mapper.writeValueAsString(path2String);
        System.out.println(json);

        path2String = mapper.readValue(json, new TypeReference<HashMap<Path, String>>() {});
        System.out.println(path2String);
    }

}

检查此链接@但是我可以反序列化
Path
实例。我在一个小测试方法中使用相同的映射器和相同的配置进行了尝试。你能发布com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge类吗?@Sambit My bad,“从账本文件写入/读取的代码:”部分是initBridge()。我还将POM简化为现在的样子。没问题,有时会发生。请检查此链接@但是我可以反序列化
Path
实例。我在一个小测试方法中使用相同的映射器和相同的配置进行了尝试。你能发布com.protonmail.sarahszabo.stellar.conversions.SpaceBridge.initBridge类吗?@Sambit My bad,“从账本文件写入/读取的代码:”部分是initBridge()。我还把POM简化成现在的样子。没问题,有时候会发生。哇,谢谢你的回答!为什么我要这么做呢?
Path
Map
没有本机Jackson支持吗?似乎有点奇怪,它可以正确地编写它,但不能读取它。@SarahSzabo,默认情况下,
Jackson
支持
Map
,因为它用于准备任何未知的
JSON对象。对于
路径
我们需要创建自定义
键反序列化器
,因为
Jackson
不知道如何从
字符串
创建它
Jackson
对于没有fit构造函数或
Jackson
注释的类需要帮助。这就是为什么我们为给定的一组类创建模块并定义各种序列化器和反序列化器。例如,看看哪个支持
java8
Time
包。如果我使用的是jdk12,并且使用的是ZonedDateTime和其他Java时间类,我需要注册JavaTimeModule吗?此外,是否有用于常见类(如
Path
)的Seralizer/Desializer库,或者我是否必须创建它?我对Jackson有点陌生,只是想了解它的基本知识。@SarahSzabo,是的,对于
Java时间
类集,您仍然需要使用
JavaTimeModule
。不,像
Path
这样的类没有预定义的序列化程序。默认情况下支持
POJO
类和原语
Path
类不是
POJO
,您需要为其创建客户序列化器/反序列化器。你可以找到一些实现。哇,谢谢你的回答!为什么我要这么做呢?
Path
Map
没有本机Jackson支持吗?似乎有点奇怪,它可以正确地编写它,但不能读取它。@SarahSzabo,默认情况下,
Jackson
支持
Map
,因为它用于准备任何未知的
JSON对象。对于
路径
我们需要创建自定义
键反序列化器
,因为
Jackson
不知道如何从
字符串
创建它
Jackson
对于没有fit构造函数或
Jackson
注释的类需要帮助。这就是为什么我们为给定的一组类创建模块并定义各种序列化器和反序列化器。例如,看看哪个支持
java8
Time
包。如果我使用的是jdk12,并且使用的是ZonedDateTime和其他Java时间类,我需要注册JavaTimeModule吗?此外,是否有用于常见类(如
Path
)的Seralizer/Desializer库,或者我是否必须创建它?我对Jackson有点陌生,只是想了解它的基本知识。@SarahSzabo,是的,对于
Java时间
类集,您仍然需要使用
JavaTimeModule
。不,像
Path
这样的类没有预定义的序列化程序。默认情况下支持
POJO
类和原语
Path
类不是
POJO
,您需要为其创建客户序列化器/反序列化器。您可以找到一些实现的。