Using Gson with Interface Types

前端 未结 6 816
生来不讨喜
生来不讨喜 2020-12-03 03:16

I am working on some server code, where the client sends requests in form of JSON. My problem is, there are a number of possible requests, all varying in small implementatio

6条回答
  •  抹茶落季
    2020-12-03 03:27

    Genson library provides support for polymorphic types by default. Here is how it would work:

    // tell genson to enable polymorphic types support
    Genson genson = new Genson.Builder().setWithClassMetadata(true).create();
    
    // json value will be {"@class":"mypackage.LoginRequest", ... other properties ...}
    String json = genson.serialize(someRequest);
    // the value of @class property will be used to detect that the concrete type is LoginRequest
    Request request = genson.deserialize(json, Request.class);
    

    You can also use aliases for your types.

    // a better way to achieve the same thing would be to use an alias
    // no need to use setWithClassMetadata(true) as when you add an alias Genson 
    // will automatically enable the class metadata mechanism
    genson = new Genson.Builder().addAlias("loginRequest", LoginRequest.class).create();
    
    // output is {"@class":"loginRequest", ... other properties ...}
    genson.serialize(someRequest);
    

提交回复
热议问题