How to remove instance type when serializing / deserializing JSON?

I use fasterxmlJSON to serialize / deserialize

public class A {
    String field;
    B b;
}

public class B {
    int n;
}

I want to get JSON in this format

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

Is it possible?

+4
source share
3 answers

You can just use @JsonUnwrapped. No custom serializers are required:

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

public class B {
    public int n;
}

Pay attention to the availability of fields or it will not work.

+1
source

You can use Jackson's annotation to provide a specific deserializer.

@JsonDeserialize(using = ADeserializer.class)
public class A {

    private String field;
    private B b;

    // ...
}

The separator for your type should look like this

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;
    }

}

Serializer. .

+2

Java .

+1

Source: https://habr.com/ru/post/1667383/


All Articles