Storing arbitrary data with GSON and Hibernate

夙愿已清 提交于 2019-12-24 08:39:15

问题


I want to persist some data relevant for the client only. I'm going to intentionally ignore database normalization here, as the data is pretty useless on the server side.

I can do it trivially by making the client convert it to JSON and include the String in the JSON send in the request. This feels pretty wrong. I tried to do something smarter and failed badly.

What I'd like to have:

Given

class MyEntity {
    String someString;
    int someInt;
    @Lob String clientData;
}

and an input

{
    someString: "The answer",
    someInt: 43,
    clientData: {
        x: [1, 1, 2, 3, 5, 8, 13],
        y: [1, 1, 2, 6, 24, 120],
        tonsOfComplicatedStuff: {stuff: stuff}
    }
}

store the clientData packed as JSON in a single column. Note that I don't want to write an adapter for MyEntity as there are many columns. I need an adapter for the single column. The column type needn't be a String (Serializable or anything else would do, as the server really doesn't care).


回答1:


Gson supports the @JsonAdapter annotation allowing to specify a JSON (de)serializer, type adapter, or even a type adapter factory. And the annotation looks like a good candidate to annotate the clientData field in MyEntity:

final class MyEntity {

    String someString;

    int someInt;

    @Lob
    @JsonAdapter(PackedJsonTypeAdapterFactory.class)
    String clientData;

}

The type adapter factory may look as follows:

final class PackedJsonTypeAdapterFactory
        implements TypeAdapterFactory {

    // Gson can instantiate this itself
    private PackedJsonTypeAdapterFactory() {
    }

    @Override
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
        @SuppressWarnings("unchecked")
        final TypeAdapter<T> typeAdapter = (TypeAdapter<T>) new PackedJsonTypeAdapter(gson);
        return typeAdapter;
    }

    private static final class PackedJsonTypeAdapter
            extends TypeAdapter<String> {

        private final Gson gson;

        private PackedJsonTypeAdapter(final Gson gson) {
            this.gson = gson;
        }

        @Override
        public void write(final JsonWriter out, final String json) {
            final JsonElement jsonElement = gson.fromJson(json, JsonElement.class);
            gson.toJson(jsonElement, out);
        }

        @Override
        public String read(final JsonReader in) {
            final JsonElement jsonElement = gson.fromJson(in, JsonElement.class);
            return jsonElement != null ? jsonElement.toString() : null;
        }

    }

}

Note that this converter strategy is implemented as a type adapter factory, since this is the only way of accessing the Gson instance known to me, and JsonSerializer/JsonDeserializer do not seem to make good parsing via the serialization context. Another pitfall here is that this implementation is tree-based requiring JSON trees to be stored in memory completely. In theory, there could be a nice stream-oriented implementation like gson.fromJson(jsonReader) -> JsonReader or a JsonReader->Reader decorator to be redirected to a StringWriter for example, but I couldn't find any alternative for really long time.

public static void main(final String... args) {
    final Gson gson = new Gson();

    out.println("deserialization:");
    final String incomingJson = "{someString:\"The answer\",someInt:43,clientData:{x:[1,1,2,3,5,8,13],y:[1,1,2,6,24,120],tonsOfComplicatedStuff:{stuff:stuff}}}";
    final MyEntity myEntity = gson.fromJson(incomingJson, MyEntity.class);
    out.println("\t" + myEntity.someString);
    out.println("\t" + myEntity.someInt);
    out.println("\t" + myEntity.clientData);

    out.println("serialization:");
    final String outgoingJson = gson.toJson(myEntity);
    out.println("\t" + outgoingJson);

    out.println("equality check:");
    out.println("\t" + areEqual(gson, incomingJson, outgoingJson));
}

private static boolean areEqual(final Gson gson, final String incomingJson, final String outgoingJson) {
    final JsonElement incoming = gson.fromJson(incomingJson, JsonElement.class);
    final JsonElement outgoing = gson.fromJson(outgoingJson, JsonElement.class);
    return incoming.equals(outgoing);
}

The output:

deserialization:  
    The answer  
    43  
    {"x":[1,1,2,3,5,8,13],"y":[1,1,2,6,24,120],"tonsOfComplicatedStuff":{"stuff":"stuff"}}  
serialization:  
    {"someString":"The answer","someInt":43,"clientData":{"x":[1,1,2,3,5,8,13],"y":[1,1,2,6,24,120],"tonsOfComplicatedStuff":{"stuff":"stuff"}}}  
equality check:  
    true  

Don't know if it can play with Hibernate nicely, though.


Edit

Despite JSON-packed strings are collected into the memory, streaming may be cheaper for various reasons and can save some memory. Another advantage of streaming is that such a JSON-packing type adapter does not need a type adapter factory anymore and Gson instances therefore keeping a JSON stream as-is, however still making some normalizations like {stuff:stuff} -> {"stuff":"stuff"}. For example:

@JsonAdapter(PackedJsonStreamTypeAdapter.class)
String clientData;
final class PackedJsonStreamTypeAdapter
        extends TypeAdapter<String> {

    private PackedJsonStreamTypeAdapter() {
    }

    @Override
    public void write(final JsonWriter out, final String json)
            throws IOException {
        @SuppressWarnings("resource")
        final Reader reader = new StringReader(json);
        writeNormalizedJsonStream(new JsonReader(reader), out);
    }

    @Override
    public String read(final JsonReader in)
            throws IOException {
        @SuppressWarnings("resource")
        final Writer writer = new StringWriter();
        writeNormalizedJsonStream(in, new JsonWriter(writer));
        return writer.toString();
    }

}
final class JsonStreams {

    private JsonStreams() {
    }

    static void writeNormalizedJsonStream(final JsonReader reader, final JsonWriter writer)
            throws IOException {
        writeNormalizedJsonStream(reader, writer, true);
    }

    @SuppressWarnings("resource")
    static void writeNormalizedJsonStream(final JsonReader reader, final JsonWriter writer, final boolean isLenient)
            throws IOException {
        int level = 0;
        for ( JsonToken token = reader.peek(); token != null; token = reader.peek() ) {
            switch ( token ) {
            case BEGIN_ARRAY:
                reader.beginArray();
                writer.beginArray();
                ++level;
                break;
            case END_ARRAY:
                reader.endArray();
                writer.endArray();
                if ( --level == 0 && isLenient ) {
                    return;
                }
                break;
            case BEGIN_OBJECT:
                reader.beginObject();
                writer.beginObject();
                ++level;
                break;
            case END_OBJECT:
                reader.endObject();
                writer.endObject();
                if ( --level == 0 && isLenient ) {
                    return;
                }
                break;
            case NAME:
                final String name = reader.nextName();
                writer.name(name);
                break;
            case STRING:
                final String s = reader.nextString();
                writer.value(s);
                break;
            case NUMBER:
                final String rawN = reader.nextString();
                final Number n;
                final Long l = Longs.tryParse(rawN);
                if ( l != null ) {
                    n = l;
                } else {
                    final Double d = Doubles.tryParse(rawN);
                    if ( d != null ) {
                        n = d;
                    } else {
                        throw new AssertionError(rawN); // must never happen
                    }
                }
                writer.value(n);
                break;
            case BOOLEAN:
                final boolean b = reader.nextBoolean();
                writer.value(b);
                break;
            case NULL:
                reader.nextNull();
                writer.nullValue();
                break;
            case END_DOCUMENT:
                // do nothing
                break;
            default:
                throw new AssertionError(token);
            }
        }
    }

}

This one parses and generates the same input and output respectively. The Longs.tryParse and Doubles.tryParse methods are taken from Google Guava.



来源:https://stackoverflow.com/questions/42494438/storing-arbitrary-data-with-gson-and-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!