how to expose class names when serializing with Gson

后端 未结 3 1025
夕颜
夕颜 2021-01-26 02:44

My scenario is very complicated but here\'s a summary:

I\'m trying to understand source of a compiler -- and to understand what each AST node represents, I\'m generating

相关标签:
3条回答
  • 2021-01-26 03:20

    Check runtimeAdapter ,

     RuntimeTypeAdapter<Node> nodeAdapter = RuntimeTypeAdapter.create(Node.class,"type");
     nodeAdapter.registerSubtype(Begin.class,"Begin");
     nodeAdapter.registerSubtype(State.class,"State");
     gsonBuilder.registerTypeHierarchyAdapter(Class.class, new GsonClassAdapter())
                .registerTypeAdapter(Node.class,nodeAdapter )
                .enableComplexMapKeySerialization().setPrettyPrinting();
     gson = gsonBuilder.create();
    
    0 讨论(0)
  • 2021-01-26 03:23

    You can also use Genson to add class name of your objects to the outputed json, just do:

    Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
    String json = genson.serialize(yourNode);
    

    The nice thing is that it enables you to deserialize back to those concrete types. See the wiki for more details.

    0 讨论(0)
  • 2021-01-26 03:32

    Gson provides an option to custom serialize and descrialize an object, by implementing the interface JsonSerializer (for serializing) and JsonDeserializer (for descralizing) you can ignore some parts of the JSON string (say _class:com.example.SomeSourceClass).

    This would also mean that a generic/regular Gson isntance will fail to read your JSON string.

    This would be a specific solution to your problem.

    Here is the Gson Userguide

    0 讨论(0)
提交回复
热议问题