Retain type annotation while converting from ION to JSON

318 Views Asked by At

I have a source from where I am getting serialized ION data with type annotated on polymorphic type fields. While converting to JSON using below code, it is losing type annotation. Is there any way to get ion type annotation as field in converted JSON?


    private final IonSystem system = IonSystemBuilder.standard().build();

    public String convert(final String serializedIon) {
        final IonValue ionValue = system.singleValue(serializedIon);

        final StringBuilder stringBuilder = new StringBuilder();
        final IonWriter writer = IonTextWriterBuilder.json().build(stringBuilder);

        ionValue.writeTo(writer);
        return stringBuilder.toString();
    }

Input ION

{matchConditions: [TypeA::{}, TypeB::{}]}

Output JSON

{"matchConditions": [{}, {}]}

Expected JSON

{"matchConditions": [{"type": "TypeA"}, {"type": "TypeB"}}

I don't have control over how ION gets serialized in source. I might be able to change it henceforth for future data but still need some way to handle already generated data.

1

There are 1 best solutions below

0
On

The IonTextWriter produced by IonTextWriterBuilder.json() follows the JSON downconversion algorithm described in the Ion Cookbook. Notice step 13, which indicates that annotations are dropped.

ion-java doesn't provide any other automatic JSON downconversion tools out of the box. You would need to write your own serialization logic to accommodate this particular use case, taking care to avoid downstream code accidentally interpreting the type field you added as real data (that is: not metadata).