当前位置: 首页 > 知识库问答 >
问题:

使用杰克逊反序列化不可变列表

李昌勋
2023-03-14

我试图让下面的例子工作:

    @Value
    @JsonDeserialize(builder = SomeClass.Builder.class)
    @Builder(builderClassName = "Builder")
    public static class SomeClass {
        @Wither
        ImmutableList<String> words;

        @JsonPOJOBuilder(withPrefix = "")
        public static class Builder {
        }
    }

    @Test
    @SneakyThrows
    public void serializeTest() {
        ObjectMapper objectMapper = new ObjectMapper();
        SomeClass someClass = SomeClass.builder()
            .words(ImmutableList.of("word1", "word2", "word3"))
            .build();
        String jsonString = objectMapper.writeValueAsString(someClass);
        log.info("serialized: {}", jsonString);
        SomeClass newSomeClass = objectMapper.readValue(jsonString, SomeClass.class);
        log.info("done");
        newSomeClass.words.forEach(w -> log.info("word {}", w));
    }

然而,它失败了

Caused by: java.lang.IllegalArgumentException: Cannot find a deserializer for non-concrete Collection type [collection type; class com.google.common.collect.ImmutableList, contains [simple type, class java.lang.String]]
    at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.createCollectionDeserializer(BasicDeserializerFactory.java:1205)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:399)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)

从这个答案中,我尝试了类似这样的做法:

    @Value
    @JsonDeserialize(builder = SomeClass.Builder.class)
    @Builder(builderClassName = "Builder")
    public static class SomeClass {
        @Wither
        @JsonDeserialize(using = ImmutableListDeserializer.class)
        ImmutableList<String> words;

        @JsonPOJOBuilder(withPrefix = "")
        public static class Builder {
        }
    }

    @Test
    @SneakyThrows
    public void serializeTest() {
        ObjectMapper objectMapper = new ObjectMapper();
        SomeClass someClass = SomeClass.builder()
            .words(ImmutableList.of("word1", "word2", "word3"))
            .build();
        String jsonString = objectMapper.writeValueAsString(someClass);
        log.info("serialized: {}", jsonString);
        SomeClass newSomeClass = objectMapper.readValue(jsonString, SomeClass.class);
        log.info("done");
        newSomeClass.words.forEach(w -> log.info("word {}", w));
    }

但这失败了:

Caused by: java.lang.IllegalArgumentException: Cannot find a deserializer for non-concrete Collection type [collection type; class com.google.common.collect.ImmutableList, contains [simple type, class java.lang.String]]

由于我正在处理的项目的限制,我无法修改对象映射器。所以我不能简单地做:

objectMapper.registerModule(new GuavaModule());

这本来是可行的。

还有其他简单的方法可以让ImmutableList反序列化工作吗?

编辑:我设法得到了一个不同的错误,如下所示:

    @Value
    @JsonDeserialize(builder = SomeClass.Builder.class)
    @Builder(builderClassName = "Builder")
    public static class SomeClass {
        @Wither
        ImmutableList<String> strings;

        @JsonPOJOBuilder(withPrefix = "")
        public static class Builder {
            @JsonDeserialize(using = ImmutableListDeserializer.class)
            public Builder strings(ImmutableList<String> strings) {
                this.strings = strings;
                return this;
            }
        }
    }

    @Test
    @SneakyThrows
    public void serializeTest() {
        ObjectMapper objectMapper = new ObjectMapper();
        SomeClass someClass = SomeClass.builder()
            .strings(ImmutableList.of("word1", "word2", "word3"))
            .build();
        String jsonString = objectMapper.writeValueAsString(someClass);
        log.info("serialized: {}", jsonString);
        SomeClass newSomeClass = objectMapper.readValue(jsonString, SomeClass.class);
        log.info("done");
        newSomeClass.strings.forEach(w -> log.info("word {}", w));
    }

这引发了:

Caused by: java.lang.IllegalArgumentException: Class com.fasterxml.jackson.datatype.guava.deser.ImmutableListDeserializer has no default (no arg) constructor

如果我可以为ImmutableListDeserializer或类似的东西构建一个无参数构造函数,也许这更容易解决

共有2个答案

姜羽
2023-03-14

最后必须编写一个自定义序列化程序。如果您有更优雅的答案,请告诉我。这是一个可能在这里结束的人的工作示例:

    @Value
    @JsonDeserialize(builder = SomeClass.Builder.class)
    @Builder(builderClassName = "Builder")
    public static class SomeClass {
        @Wither
        ImmutableList<String> strings;

        @JsonPOJOBuilder(withPrefix = "")
        public static class Builder {
            @JsonDeserialize(using = CustomDeserializer.class)
            public Builder strings(ImmutableList<String> strings) {
                this.strings = strings;
                return this;
            }
        }
    }

    public static class CustomDeserializer extends StdDeserializer<ImmutableList<String>> {
        public CustomDeserializer() {
            super(ImmutableList.class);
        }

        @Override
        public ImmutableList<String> deserialize(JsonParser parser, DeserializationContext deserializer) throws IOException {
            ImmutableList.Builder<String> immutableListBuilder = ImmutableList.builder();
            while (!parser.isClosed()) {
                JsonToken jsonToken = parser.nextToken();
                if (JsonToken.VALUE_STRING.equals(jsonToken)) {
                    final String fieldValue = parser.getValueAsString();
                    immutableListBuilder.add(fieldValue);
                } else if (JsonToken.END_ARRAY.equals(jsonToken)) {
                    break;
                }
            }
            return immutableListBuilder.build();
        }
    }

    @Test
    @SneakyThrows
    public void serializeTest() {
        ObjectMapper objectMapper = new ObjectMapper();
        SomeClass someClass = SomeClass.builder()
            .strings(ImmutableList.of("word1", "word2", "word3"))
            .build();
        String jsonString = objectMapper.writeValueAsString(someClass);
        log.info("serialized: {}", jsonString);
        SomeClass newSomeClass = objectMapper.readValue(jsonString, SomeClass.class);
        log.info("done");
        newSomeClass.strings.forEach(w -> log.info("word {}", w));
    }

我发现了一篇非常好的文章:http://tutorials.jenkov.com/java-json/jackson-objectmapper.html

陈茂
2023-03-14
  1. 让 IDE 生成构造函数
  2. 向构造函数添加@JsonCreator
  3. 添加参数名称模块
  4. 番石榴模块添加到映射器。
  5. 使用 -parameters 标志进行编译

import org.junit.jupiter.api.Test;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.guava.GuavaModule;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.google.common.collect.ImmutableList;

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Singular;
import lombok.Value;
import lombok.With;
import lombok.extern.log4j.Log4j2;

@SuppressWarnings("javadoc")
@Log4j2
public class Q61900327 {

    /**
     * We add the ParameterNamesModule so Jackson can use the constructor arguments to
     * properly map the fields.
     */
    static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new GuavaModule())
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module());

    /**
     * This solution works at the cost of having the IDE generate the constructor.
     */
    static class ExplicitConstructorSolution {

        @Value
        @Builder(toBuilder = true)
        public static class SomeClass {

            @With
            @Singular
            private ImmutableList<String> words;

            @JsonCreator
            public SomeClass(ImmutableList<String> words) {
                super();
                this.words = words;
            }
        }

        @Test
        void serializeTest() throws JsonProcessingException {


            var someClass = SomeClass.builder()
                    .word("word1")
                    .word("word2")
                    .word("word3")
                    .build();

            try {
                var jsonString = OBJECT_MAPPER.writeValueAsString(someClass);
                log.info("serialized: {}", jsonString);
                var newSomeClass = OBJECT_MAPPER.readValue(jsonString, SomeClass.class);
                newSomeClass.words.forEach(w -> log.info("word {}", w));
            }
            catch (JsonProcessingException e) {
                log.error("someClass could not roundtrip.", e);
                throw e;
            }
        }
    }

    /**
     * Note this solution looks great but unfortunately will cause javadoc to fail with:
     * <p>
     * {@code
     * error: cannot find symbol  [ERROR] @AllArgsConstructor(access = AccessLevel.PUBLIC, onConstructor_ =
     * { @JsonCreator })}
     * <p>
     * @see <a href="https://github.com/rzwitserloot/lombok/issues/2137">lombok #2137</a>
     *
     */
    static class OnConstructorSolution {

        @Value
        @AllArgsConstructor(access = AccessLevel.PUBLIC, onConstructor_ = { @JsonCreator })
        @Builder(toBuilder = true)
        public static class SomeClass {

            @With
            @Singular
            private ImmutableList<String> words;
        }

        @Test
        void serializeTest() throws JsonProcessingException {

            var someClass = SomeClass.builder()
                    .word("word1")
                    .word("word2")
                    .word("word3")
                    .build();

            try {
                var jsonString = OBJECT_MAPPER.writeValueAsString(someClass);
                log.info("serialized: {}", jsonString);
                var newSomeClass = OBJECT_MAPPER.readValue(jsonString, SomeClass.class);
                newSomeClass.words.forEach(w -> log.info("word {}", w));
            }
            catch (JsonProcessingException e) {
                log.error("someClass could not roundtrip.", e);
                throw e;
            }
        }
    }

}


pom:


<?xml version="1.0" encoding="UTF-8" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>io.jeffmaxwell.stackoverflow</groupId>
  <artifactId>stackoverflow</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
    <maven.compiler.source>14</maven.compiler.source>
    <maven.compiler.target>14</maven.compiler.target>
    <maven.compiler.release>14</maven.compiler.release>
    <maven.compiler.parameters>true</maven.compiler.parameters>
    <maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
    <maven.compiler.showWarnings>true</maven.compiler.showWarnings>
    <maven.compiler.verbose>true</maven.compiler.verbose>

    <maven-dependency-plugin.version>3.1.2</maven-dependency-plugin.version>

    <guava.version>29.0-jre</guava.version>
    <junit.version>5.6.2</junit.version>
    <log4j2.version>2.13.3</log4j2.version>
    <jackson.version>2.11.0</jackson.version>
    <lombok.version>1.18.12</lombok.version>
  </properties>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>${maven-compiler-plugin.version}</version>
        </plugin>

        <plugin>
          <artifactId>maven-dependency-plugin</artifactId>
          <version>${maven-dependency-plugin.version}</version>
          <configuration>
            <outputXML>true</outputXML>
            <verbose>true</verbose>
          </configuration>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>${guava.version}</version>
      </dependency>

      <dependency>
        <groupId>org.junit</groupId>
        <artifactId>junit-bom</artifactId>
        <version>${junit.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

      <dependency>
        <groupId>com.fasterxml.jackson</groupId>
        <artifactId>jackson-bom</artifactId>
        <version>${jackson.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-bom</artifactId>
        <version>${log4j2.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>

      <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>${lombok.version}</version>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-guava</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.datatype</groupId>
      <artifactId>jackson-datatype-jdk8</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.module</groupId>
      <artifactId>jackson-module-parameter-names</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-1.2-api</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-jcl</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <scope>runtime</scope>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <scope>runtime</scope>
    </dependency>
  </dependencies>
</project>

 类似资料:
  • 问题内容: 我有一个JSON字符串,将标记为而不是。因此,例如,如果我有一个没有子对象的对象,我将收到类似以下的字符串: 我想将其反序列化为Parent类,并将子级正确设置为一个空的子级列表。 对于上述JSON字符串,我想要一个对象,其设置为,而设置为。 我会知道如何在整个课堂上使用注释 然后 但是,我想解决一个从字符串正确实例化List的一般问题: 我能得到类似的东西吗? 问题答案: 几个选择;

  • 问题内容: 我有一个这样的模型: 例如,我从远程获取以下JSON: 当我反序列化此JSON时,and 变量将获得正确的值。但是,我不想解释变量的内容。相反,我希望它是以下字符串: 之后,我将自己解释。我如何获得这个值? 问题答案: Jackson问题596是为原始问题中描述的所需功能而创建的。如果要实施,请投票。 当前可用的解决方案是实现自定义反序列化处理。

  • 问题内容: 我正在创建具有嵌套列表的API。杰克逊似乎是创建对象的好工具,但我还不太清楚如何嵌套列表,我想知道它是否可能。 我的对象看起来像这样。 我希望有一种将其映射到看起来像这样的json的方法: 我们希望能够做到这一点,因此我们可以将属性添加到列表中。 问题答案: 您可以为编写自定义解串器。请参见以下示例: 现在,您必须通知Jackson将其用于您的财产。您可以通过以下方式执行此操作:

  • 我明白它无法从嵌套JSON反序列化字符串。我解决这个问题的一个方法是通过编写自定义映射器 但是只要pojo中有变化,这就需要修改映射器,添加/删除字段。Mixin工作时没有任何变化,我该如何更新我的Mixin来处理objectId呢?

  • 我想用scala中的jackson反序列化json json_结构: {“type”:“struct”,“fields”:[{“name”:“code_role”,“type”:“string”,“nullable”:true,“metadata”:{“HIVE_type_string”:“string”},{“name”:“libelle_role”,“type”:“string”,“nulla

  • 问题内容: 我有一个Java类,我对从JSON反序列化感兴趣。我已经配置了一个特殊的MixIn类,以帮助我进行反序列化。只有和实例变量与适当的getter和setter方法相结合。看起来像这样: 在我的测试客户端中,我执行以下操作,但是在编译时它当然不起作用,因为与类型不匹配有关。 我知道我可以通过创建一个仅包含一个“响应”对象的方法来缓解此问题,但是随后我将不得不为我想返回的每种类型创建这些有点