bluelinelabs / LoganSquare

Screaming fast JSON parsing and serialization library for Android.
Apache License 2.0
3.21k stars 306 forks source link

deserialize an object using a facade pattern #121

Open ellsworthrw opened 8 years ago

ellsworthrw commented 8 years ago

Ran into a wall trying to write a converter for a class using a facade pattern. Here are my classes: @JsonObject class Ribbon { @JsonField List tiles }

class TileAsset { private Metadata metadata public TileAsset(Metadata metadata) { mMetadata = metadata; } }

@JsonObject class Metadata { }

I am trying to write a type converter but have not found a way to implement it. This is an attempt:

public static class TileAssetConverter implements TypeConverter { @Override public TileAsset parse(JsonParser jsonParser) throws IOException { Mlog.d(TAG, "parse(%s)", jsonParser.getInputSource()); if (jsonParser.getInputSource() instanceof InputStream) { // PROBLEM: jsonParser.getInputSource() is always null: need a way to get the input stream // Next problem: is that jackson's parser needs to advance past this object when done Metadata metadata = LoganSquare.parse((InputStream) jsonParser.getInputSource(), Metadata.class); return new TileAsset(metadata); } return null; }

    @Override
    public void serialize(TileAsset object, String fieldName, boolean writeFieldNameForObject, JsonGenerator jsonGenerator) throws IOException {
        if (fieldName != null) {
            jsonGenerator.writeStringField(fieldName, Utils.toJSON(object.mMetadata));
        } else {
            jsonGenerator.writeString(Utils.toJSON(object.mMetadata));
        }
    }
}
ellsworthrw commented 8 years ago

The following works but it is a hack and is brittle:

public static class TileAssetConverter implements TypeConverter<TileAsset> {
    @Override
    public TileAsset parse(JsonParser jsonParser) throws IOException {
        Metadata metadata = JsonMapperLoaderImpl.COM_MOVENETWORKS_MODEL_METADATA__JSONOBJECTMAPPER.parse(jsonParser);
        return new TileAsset(metadata);
    }

}

There has to be a more safe way of doing this.