使用GSon将JSon转换为多个未知的Java对象类型 [英] Convert from JSon to multiple unknown java object types using GSon

查看:161
本文介绍了使用GSon将JSon转换为多个未知的Java对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个netty解码器,它使用GSon将来自Web客户端的JSon转换为适当的java对象。
要求是:
客户端可以发送不相关的类,A类,B类,C类等,但我想在管道中使用相同的单例解码器实例做转换(因为我用spring来配置它)。我面临的问题是我需要事先知道对象。

  public Object decode()
{
gson.fromJson(jsonString,A.class);
}

这不能解码B或C.我的库的用户现在需要为每个类编写单独的解码器,而不是在后续的下一次投射。我唯一可以看到的做法是从Web客户端将JSon字符串中的类名称org.example.C传递给解析器,然后使用 Class .forName 来获得该类。有没有更好的方法来做到这一点?

解决方案

GSon必须知道匹配json字符串的类。如果你不想从json()中提供它,你实际上可以在Json中指定它。一种方法是定义一个接口并在其上绑定一个适配器。



像:

  class A implements MyInterface {
// ...
}

public Object decode()
{
Gson gson = builder .registerTypeAdapter(MyInterface.class,new MyInterfaceAdapter());
MyInterface a = gson.fromJson(jsonString,MyInterface.class);

$ / code $ / pre
$ b $适配器可以像:

  public final class MYInterfaceAdapter实现了JsonDeserializer< MyInterface> ;, JsonSerializer< MyInterface> {
private static final String PROP_NAME =myClass;
$ b $ @Override
public MyInterface deserialize(JsonElement json,Type typeOfT,JsonDeserializationContext context)throws JsonParseException {
try {
String classPath = json.getAsJsonObject()。getAsJsonPrimitive (PROP_NAME).getAsString();
Class< MyInterface> cls =(Class< MyInterface>)Class.forName(classPath);

return(MyInterface)context.deserialize(json,cls);
} catch(ClassNotFoundException e){
e.printStackTrace();
}

返回null;

$ b @Override
public JsonElement serialize(MyInterface src,Type typeOfSrc,JsonSerializationContext context){
//注意:不起作用,您必须委派它
JsonObject jo = context.serialize(src).getAsJsonObject();

String classPath = src.getClass()。getName();
jo.add(PROP_NAME,new JsonPrimitive(classPath));

return jo;
}
}


I have a netty decoder which uses GSon to convert JSon coming from web client to appropriate java objects. The requirement is: Client could be sending unrelated classes, Class A, Class B, Class C etc but I would like to use the same singleton decoder instance in the pipeline to do conversion(since I use spring for configuring it). The issue I am facing is I need to know the class object before hand.

public Object decode()
{
    gson.fromJson(jsonString, A.class);
}

This cannot decode B or C. The users of my library, now need to write separate decoders for each class instead of a cast later down the line. The only way I can see for doing this is to pass the String name of the class say "org.example.C" in the JSon string from web client, parse it out in the decoder and then use Class.forName to get the class. Is there a better way to do this?

解决方案

GSon MUST know the class matching the json string. If you don't wan't to provide it with fromJson(), you can actually specify it in the Json. A way is to define an interface and bind an adapter on it.

Like :

  class A implements MyInterface {
    // ...
  }

  public Object decode()
  {
    Gson  gson = builder.registerTypeAdapter(MyInterface.class, new MyInterfaceAdapter());
    MyInterface a =  gson.fromJson(jsonString, MyInterface.class);
  }

Adapter can be like :

public final class MYInterfaceAdapter implements JsonDeserializer<MyInterface>, JsonSerializer<MyInterface> {
  private static final String PROP_NAME = "myClass";

  @Override
  public MyInterface deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    try {
      String classPath = json.getAsJsonObject().getAsJsonPrimitive(PROP_NAME).getAsString();
      Class<MyInterface> cls = (Class<MyInterface>) Class.forName(classPath);

      return (MyInterface) context.deserialize(json, cls);
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    return null;
  }

  @Override
  public JsonElement serialize(MyInterface src, Type typeOfSrc, JsonSerializationContext context) {
    // note : won't work, you must delegate this
    JsonObject jo = context.serialize(src).getAsJsonObject();

    String classPath = src.getClass().getName();
    jo.add(PROP_NAME, new JsonPrimitive(classPath));

    return jo;
  }
}

这篇关于使用GSon将JSon转换为多个未知的Java对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆