25

我有一个 JSON 对象,例如:

{"name":"John", "grade":"A"}

或者

{"name":"Mike", "grade":"B"}

或者

{"name":"Simon", "grade":"C"}

ETC

我正在尝试将上面的 JSON 映射到:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee{
      @JsonIgnoreProperties(ignoreUnknown = true)
      public enum Grade{ A, B, C }
      Grade grade;
      String name;

  public Grade getGrade() {
    return grade;
  }

  public void setGrade(Grade grade) {
    this.grade = grade;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

上述映射工作正常,但将来会有更多“等级”类型,比如 D、E 等,这会破坏现有映射并引发以下异常

05-08 09:56:28.130: W/System.err(21309): org.codehaus.jackson.map.JsonMappingException: Can not construct instance of Employee from String value 'D': value not one of declared Enum instance names

有没有办法忽略枚举类型中的未知字段?

谢谢

4

5 回答 5

29

我找到了一种方法,如下所示:

public static void main(String[] args) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
    String json = "{\"name\":\"John\", \"grade\":\"D\"}";

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
    Employee employee = mapper.readValue(new ByteArrayInputStream(json.getBytes("UTF-8")), Employee.class);

    System.out.println(employee.getGrade());
}

这输出:

无效的

其他类:

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee {
    private String name;
    private Grade grade;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }
}



import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public enum Grade {A, B, C}

我还没有遇到用注释来做到这一点的方法。

我希望这有帮助。

于 2013-05-08T17:52:05.297 回答
22

我认为您应该为枚举定义外部反序列化器。Grade

我向枚举添加了附加字段 - 未知:

enum Grade {
    A, B, C, UNKNOWN;

    public static Grade fromString(String value) {
        for (Grade grade : values()) {
            if (grade.name().equalsIgnoreCase(value)) {
                return grade;
            }
        }

        return UNKNOWN;
    }
}
class Employee {

    @JsonDeserialize(using = GradeDeserializer.class)
    private Grade grade;
    private String name;

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Employee [grade=" + grade + ", name=" + name + "]";
    }
}

现在,解析器可能看起来像这样:

class GradeDeserializer extends JsonDeserializer<Grade> {
    @Override
    public Grade deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {
        return Grade.fromString(parser.getValueAsString());
    }
}

示例用法:

public class JacksonProgram {

    public static void main(String[] args) throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonFactory jsonFactory = new JsonFactory();
        JsonParser parser = jsonFactory
                .createJsonParser("{\"name\":\"John\", \"grade\":\"D\"}");
        Employee employee = objectMapper.readValue(parser, Employee.class);
        System.out.println(employee);
    }

}

输出:

Employee [grade=UNKNOWN, name=John]

例如,如果您不想添加其他字段,则可以返回null

于 2013-05-08T17:47:41.023 回答
12

@JsonCreator相比 . 提供了更简洁的解决方案@JsonDeserialize

这个想法是用你的实现注释你的valueOf()替换(safeValueOf()在这个例子中调用),@JsonCreator然后杰克逊将使用你的实现反序列化字符串。

请注意,实现在枚举内部,您可以将其用作其他对象中的字段而无需更改。

下面的解决方案包含在单元测试中,因此您可以直接运行它。

import static junit.framework.TestCase.assertEquals;

import java.io.IOException;

import org.junit.Test;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.ObjectMapper;

public class EmployeeGradeTest {

    public enum Grade {
        A, B, C, OTHER;

        @JsonCreator
        public static Grade safeValueOf(String string) {
            try {
                return Grade.valueOf(string);
            } catch (IllegalArgumentException e) {
                return OTHER;
            }
        }
    }

    @Test
    public void deserialize() throws IOException {
        assertEquals(Grade.A, new ObjectMapper().readValue("\"A\"", Grade.class));
    }

    @Test
    public void deserializeNewValue() throws IOException {
        assertEquals(Grade.OTHER, new ObjectMapper().readValue("\"D\"", Grade.class));
    }
}
于 2017-10-09T20:41:45.333 回答
5

我正在使用 boot2(尽管这也可以在 boot 1 中使用),但您可以在应用程序属性/yaml 中启用反序列化功能;

spring:
  jackson:
    deserialization:
      READ_UNKNOWN_ENUM_VALUES_AS_NULL: true
于 2019-11-09T01:16:47.907 回答
3

有两种方法可以处理此类情况:

选项 1:将未知的枚举值替换为null

对于READ_UNKNOWN_ENUM_VALUES_AS_NULL您的ObjectMapper. 在此之后,当您解析具有未知枚举字段值的对象时,它将被反序列化为null. 请参阅下面的示例代码:

import com.fasterxml.jackson.databind.*;

public static ObjectMapper getMapper() {
    return ObjectMapper().enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);
}

选项 2:将未知枚举值替换为默认枚举值(例如UNKNOWN

为此,首先READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE在您的ObjectMapper. 然后,在你的枚举类中用 . 注释你想用作默认枚举值的元素@JsonEnumDefaultValue。请参阅下面的代码示例:

import com.fasterxml.jackson.databind.*;

public static ObjectMapper getMapper() {
    return ObjectMapper().enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE);
}


public enum YourEnum {
   A,
   B,
   C,
   @JsonEnumDefaultValue UNKNOWN;

}
于 2020-10-30T15:22:12.037 回答