Skip to content

Can not deserialize json to enum value with Object-/Array-valued input, @JsonCreator #3280

@peteryuanpan

Description

@peteryuanpan

Describe the bug
can not deserialize json to enum value in a particular case

Version information
Which Jackson version(s) was this for?
2.11.0

To Reproduce
If you have a way to reproduce this with:

  1. Brief code sample/snippet: include here in preformatted/code section
package server.test202109;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fenbi.common.util.IgnorableObjectMapper;

import java.io.IOException;

/**
 * @author peteryuanpan
 */
public class TestJackSon {

    private static final String json1 = "{\"b\":\"x\"}";
    private static final String json2 = "{\"a\":\"1\", \"b\":\"x\"}";
    private static final String json3 = "{\"a\":[], \"b\":\"x\"}";
    private static final String json4 = "{\"a\":{}, \"b\":\"x\"}";
    private static final String json5 = "{\"b\":\"x\", \"a\":[]}";
    private static final String json6 = "{\"b\":\"y\", \"a\":{}}";

    private static final IgnorableObjectMapper objectMapper = new IgnorableObjectMapper();

    public static void main(String[] args) throws IOException {
        test(json1);
        test(json2);
        test(json3);
        test(json4);
        test(json5);
        test(json6);
    }

    private static void test(String json) throws IOException {
        Enum e = objectMapper.readValue(json, Enum.class);
        System.out.println(e == null);
    }

    enum Enum {
        x("x"),
        y("y"),
        z("z");
        private final String value;
        Enum(String value) {
            this.value = value;
        }
        @JsonCreator
        public static Enum getByValue(@JsonProperty("b") String value) {
            for (Enum e : Enum.values()) {
                if (e.value.equals(value)) {
                    return e;
                }
            }
            return null;
        }
    }
}
  1. Longer example stored somewhere else (diff repo, snippet), add a link
  2. Textual explanation: include here
    The output is
false
false
true
true
false
false

can not deserialize json3 and json4, because there is "]" or "}" before the parameter "b"

Expected behavior
all output is false

Additional context
Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions