杰克逊配置将枚举写为对象

时间:2011-11-25 00:30:26

标签: serialization enums deserialization jackson

当我尝试序列化和反序列化Set<ClassA<?>>通用对象时,如下所示:

public class ClassA<T> {

private ClassB datum;
private T value;
...
}

如果T恰好是枚举,则会将其写为String值。这对于序列化很好,但是当我反序列化时,不可能知道String值是否为enum。杰克逊然后将结果对象变成一个字符串,你得到一个ClassA<String>而不是ClassA<SomeEnumType>

杰克逊是否有配置让它创建一些提示值是枚举?或者可能将枚举转换为JSON对象而不是字符串值?

1 个答案:

答案 0 :(得分:1)

  

杰克逊是否有配置让它创建一些值为枚举的提示?

可以从匹配的JSON字符串值反序列化为枚举实例。或者这在某种程度上不适用于您的情况?

这是一个例子。

import java.util.Set;
import java.util.TreeSet;

import org.codehaus.jackson.annotate.JsonAutoDetect.Visibility;
import org.codehaus.jackson.annotate.JsonMethod;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper().setVisibility(JsonMethod.FIELD, Visibility.ANY);

    String myEnumJson = mapper.writeValueAsString(MyEnum.MyEnum1);

    System.out.println(myEnumJson);

    MyEnum myEnum = mapper.readValue(myEnumJson, MyEnum.class);

    System.out.println(myEnum);

    Set<ClassA<MyEnum>> set = new TreeSet<ClassA<MyEnum>>();
    set.add(new ClassA<MyEnum>(new ClassB("bValue7"), MyEnum.MyEnum1));
    set.add(new ClassA<MyEnum>(new ClassB("bValue8"), MyEnum.MyEnum2));
    String setJson = mapper.writeValueAsString(set);
    System.out.println(setJson);

    TypeFactory typeFactory = TypeFactory.defaultInstance();

    Set<ClassA<MyEnum>> setCopy = mapper.readValue(setJson,
        typeFactory.constructCollectionType(Set.class,
            typeFactory.constructParametricType(ClassA.class, MyEnum.class)));
    System.out.println(setCopy);
  }
}

class ClassA<T> implements Comparable<ClassA<T>>
{
  ClassB datum;
  T value;

  ClassA()
  {
  }

  ClassA(ClassB datum, T value)
  {
    this.datum = datum;
    this.value = value;
  }

  @Override
  public int compareTo(ClassA<T> o)
  {
    return 42;
  }

  @Override
  public String toString()
  {
    return String.format("ClassA: datum=%s, value=%s", datum, value);
  }
}

class ClassB
{
  String bValue;

  ClassB()
  {
  }

  ClassB(String bValue)
  {
    this.bValue = bValue;
  }

  @Override
  public String toString()
  {
    return String.format("ClassB: bValue=%s", bValue);
  }
}

enum MyEnum
{
  MyEnum1("myEnum1", 1), MyEnum2("myEnum2", 2);

  String name;
  int id;

  MyEnum(String name, int id)
  {
    this.name = name;
    this.id = id;
  }
}

输出:

"MyEnum1"
MyEnum1
[{"datum":{"bValue":"bValue7"},"value":"MyEnum1"},{"datum":{"bValue":"bValue8"},"value":"MyEnum2"}]
[ClassA: datum=ClassB: bValue=bValue7, value=MyEnum1, ClassA: datum=ClassB: bValue=bValue8, value=MyEnum2]

如果出于某种原因需要将枚举序列化为POJO,则需要进行自定义序列化处理。 Serializing enums with Jackson