【问题标题】:How to erase a type of instance when serializing/deserializing JSON?序列化/反序列化 JSON 时如何擦除一种类型的实例?
【发布时间】:2017-01-20 17:06:06
【问题描述】:

我使用fasterxml 来序列化/反序列化 JSON

public class A {
    String field;
    B b;
}

public class B {
    int n;
}

我想得到这样格式的 JSON

{
  "field": "abc",
  "n": 123
}

有可能吗?

【问题讨论】:

    标签: java json serialization deserialization fasterxml


    【解决方案1】:

    您可以使用 Jackson 注释来提供特定的反序列化器。

    @JsonDeserialize(using = ADeserializer.class)
    public class A {
    
        private String field;
        private B b;
    
        // ...
    }
    

    你的类型的反序列化器应该是这样的

    public class ADeserializer extends JsonDeserializer<A> {
    
        @Override
        public A deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
            ObjectCodec codec = p.getCodec();
            JsonNode node = codec.readTree(p);
    
            String field = node.get("field").asText();
            int n = node.get("n").asInt();
    
            A a = new A();
            B b = new B();
    
            b.setN(n);
    
            a.setField(field);
            a.setB(b);
    
            return a;
        }
    
    }
    

    对于序列化,可以使用自定义序列化器。就是这样。

    【讨论】:

      【解决方案2】:

      您可以简单地使用@JsonUnwrapped。不需要自定义序列化程序:

      public class A {
          public String field;
          @JsonUnwrapped
          public B b;
      }
      
      public class B {
          public int n;
      }
      

      注意字段的可访问性,否则它将不起作用。

      【讨论】:

        【解决方案3】:

        在 Java 中没有办法做到这一点。

        【讨论】:

        • 正如 Alex 在 his answer 中演示的那样,这是可能的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-01
        • 1970-01-01
        • 2013-12-15
        相关资源
        最近更新 更多