代码之家  ›  专栏  ›  技术社区  ›  GolamMazid Sajib

pojo类名序列化[重复]

  •  -1
  • GolamMazid Sajib  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我想用自定义名称而不是类名序列化

    我很清楚 this . 请不要参考这个答案。

    如何用Jackson序列化pojo类名。 例子:

    public class A{
    private int a;
    //getter seeter
    }
    

    当序列化一个想要像:

    {"a": 1,"class":"ARequest"}
    

    如何使用给定的 className . 有没有可能没有超控 toString() 方法。我在改进后的方法体中使用了这个类。

    有一点我不在类名下序列化它,比如:

    {"ARequest":{"a":5}}
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   cassiomolin    6 年前

    @JsonTypeInfo

    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="class")
    public class Foo {
    
        public String bar;
    
        // Getters and setters
    }
    

    ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writer().withDefaultPrettyPrinter().writeValueAsString(foo));
    

    {
      "class" : "Foo",
      "bar" : "test"
    }
    

    org.example.Foo JsonTypeInfo.Id.CLASS JsonTypeInfo.Id.NAME

        2
  •  1
  •   Halko Karr-Sajtarevic    6 年前

    @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="class") here