【问题标题】:Code Design: JSON from Socket to custom handler class代码设计:从 Socket 到自定义处理程序类的 JSON
【发布时间】:2017-03-02 12:03:29
【问题描述】:

我有一个 Java 套接字服务器。此套接字将接收具有特定结构的 json 字符串。

{
    "command": "test",
    "name": "Hallo Welt"
}

我无法更改此结构。 “command”的值将声明内容的类型。

从套接字接收到这个后,我想调用不同的处理程序来处理这些不同的命令:

  • command "test" > TestHandler 实现 CommandHandler
  • command "foo" > FooHandler 实现 CommandHandler

如何将 json 转换为对象并将对象绑定到特定的处理程序?

这是我目前的做法: 我有一个名为 BaseCommand 的模型类,其中包含一个枚举命令字段。

class BaseCommand {
    public CommandType command;
}

class TestCommand extends BaseCommand {
    public String name;
}

使用 GSON,我将 JSON 解析为 BaseCommand 类。 之后我可以读取命令类型。

我声明了一个 ENUM 来将命令类型映射到 Handler:

enum CommandType {
    test(TestHandler.class),
    foo(FooHandler.class);

    public final Class<? extends CommandHandler> handlerClass;        

    public CommandTypes(Class<? extends CommandHandler> handlerClass) {
        this.handlerClass = handlerClass;
    }
}

我的处理程序正在实现这个接口:

public interface CommandHandler<T extends BaseCommand> {
    void handle(T command);
}

现在我有了命令类型 enum 并通过 Google Guice MapBinder 我可以获取 Handler 实例来处理请求。这行得通

// in class ...
private final Map<CommandType, CommandHandler> handlers;

@Inject ClassName(Map<CommandType, CommandHandler> handlers) {
    this.handlers = handlers;
}

// in converter method
private void convert(String json) {
    BaseCommand baseCommand = GSONHelper().fromJson(json, BaseCommand.class);

    // How can I get the CommandModel? 
    // If the commandType is "test" how can I parse TestCommand automatically?

    ??? commandModel = GSONHelper().fromJson(json, ???);

    handlers.get(baseCommand.command).handle(commandModel);
}

有人知道我的问题的解决方案吗? 或者完全不同的方法?

最好的问候,迈克尔

【问题讨论】:

    标签: java json generics gson guice


    【解决方案1】:

    如何获得 CommandModel?
    如果 commandType 是“test”,我该如何自动解析 TestCommand?

    您可以使用TypeAdapterFactory 以最准确、最灵活的方式获得最合适的类型适配器。下面的示例与您的类命名略有不同,但我认为这对您来说不是一个大问题。因此,假设您有以下命令参数 DTO 声明:

    abstract class AbstractCommandDto {
    
        final String command = null;
    
    }
    
    final class HelloCommandDto
            extends AbstractCommandDto {
    
        final String name = null;
    
    }
    

    现在您可以创建一个特殊的TypeAdapterFactory 来进行某种预测,以通过命令参数名称确定传入的命令。它可能看起来很复杂,但实际上TypeAdapterFactoryies 并不难实现。请注意,JsonDeserializer 可能是您的另一个选择,但除非您将其 deserialize() 方法委托给另一个支持 Gson 实例,否则您将失去自动反序列化。

    final class AbstractCommandDtoTypeAdapterFactory
            implements TypeAdapterFactory {
    
        // The factory handles no state and can be instantiated once    
        private static final TypeAdapterFactory abstractCommandDtoTypeAdapterFactory = new AbstractCommandDtoTypeAdapterFactory();
    
        // Type tokens are used to define type information and are perfect value types so they can be instantiated once as well
        private static final TypeToken<CommandProbingDto> abstractCommandProbingDtoTypeToken = new TypeToken<CommandProbingDto>() {
        };
    
        private static final TypeToken<HelloCommandDto> helloCommandDtoTypeToken = new TypeToken<HelloCommandDto>() {
        };
    
        private AbstractCommandDtoTypeAdapterFactory() {
        }
    
        static TypeAdapterFactory getAbstractCommandDtoTypeAdapterFactory() {
            return abstractCommandDtoTypeAdapterFactory;
        }
    
        @Override
        public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> typeToken) {
            // First, check if the incoming type is AbstractCommandDto
            if ( AbstractCommandDto.class.isAssignableFrom(typeToken.getRawType()) ) {
                // If yes, then build a special type adapter for the concrete type
                final TypeAdapter<AbstractCommandDto> abstractCommandDtoTypeAdapter = new AbstractCommandDtoTypeAdapter(
                        gson,
                        gson.getDelegateAdapter(this, abstractCommandProbingDtoTypeToken),
                        (commandName, jsonObject) -> deserialize(gson, commandName, jsonObject),
                        dto -> getTypeAdapter(gson, dto)
                );
                // Some cheating for javac...
                @SuppressWarnings("unchecked")
                final TypeAdapter<T> typeAdapter = (TypeAdapter<T>) abstractCommandDtoTypeAdapter;
                return typeAdapter;
            }
            // If it's something else, just let Gson pick up the next type adapter
            return null;
        }
    
        // Create an AbstractCommandDto instance out of a ready to use JsonObject (see the disadvantages about JSON trees below)
        private AbstractCommandDto deserialize(final Gson gson, final String commandName, final JsonObject jsonObject) {
            @SuppressWarnings("unchecked")
            final TypeToken<AbstractCommandDto> typeToken = (TypeToken<AbstractCommandDto>) resolve(commandName);
            final TypeAdapter<AbstractCommandDto> typeAdapter = gson.getDelegateAdapter(this, typeToken);
            return typeAdapter.fromJsonTree(jsonObject);
        }
    
        private TypeAdapter<AbstractCommandDto> getTypeAdapter(final Gson gson, final AbstractCommandDto dto) {
            @SuppressWarnings("unchecked")
            final Class<AbstractCommandDto> clazz = (Class<AbstractCommandDto>) dto.getClass();
            return gson.getDelegateAdapter(this, TypeToken.get(clazz));
        }
    
        // Or any other way to resolve the class. This is just for simplicity and can be even extract elsewhere from the type adapter factory class
        private static TypeToken<? extends AbstractCommandDto> resolve(final String commandName)
                throws IllegalArgumentException {
            switch ( commandName ) {
            case "hello":
                return helloCommandDtoTypeToken;
            default:
                throw new IllegalArgumentException("Cannot handle " + commandName);
            }
        }
    
        private static final class AbstractCommandDtoTypeAdapter
                extends TypeAdapter<AbstractCommandDto> {
    
            private final Gson gson;
            private final TypeAdapter<CommandProbingDto> probingTypeAdapter;
            private final BiFunction<? super String, ? super JsonObject, ? extends AbstractCommandDto> commandNameToCommand;
            private final Function<? super AbstractCommandDto, ? extends TypeAdapter<AbstractCommandDto>> commandToTypeAdapter;
    
            private AbstractCommandDtoTypeAdapter(
                    final Gson gson,
                    final TypeAdapter<CommandProbingDto> probingTypeAdapter,
                    final BiFunction<? super String, ? super JsonObject, ? extends AbstractCommandDto> commandNameToCommand,
                    final Function<? super AbstractCommandDto, ? extends TypeAdapter<AbstractCommandDto>> commandToTypeAdapter
            ) {
                this.gson = gson;
                this.probingTypeAdapter = probingTypeAdapter;
                this.commandNameToCommand = commandNameToCommand;
                this.commandToTypeAdapter = commandToTypeAdapter;
            }
    
            @Override
            public void write(final JsonWriter out, final AbstractCommandDto dto)
                    throws IOException {
                // Just pick up a delegated type adapter factory and use it
                // Or just throw an UnsupportedOperationException if you're not going to serialize command arguments
                final TypeAdapter<AbstractCommandDto> typeAdapter = commandToTypeAdapter.apply(dto);
                typeAdapter.write(out, dto);
            }
    
            @Override
            public AbstractCommandDto read(final JsonReader in) {
                // Here you can two ways:
                // * Either "cache" the whole JSON tree into memory (JsonElement, etc,) and simplify the command peeking
                // * Or analyze the JSON token stream in a more efficient and sophisticated way
                final JsonObject jsonObject = gson.fromJson(in, JsonObject.class);
                final CommandProbingDto commandProbingDto = probingTypeAdapter.fromJsonTree(jsonObject);
                // Or just jsonObject.get("command") and even throw abstractCommandDto, AbstractCommandProbingDto and all of it gets away
                final String commandName = commandProbingDto.command;
                return commandNameToCommand.apply(commandName, jsonObject);
            }
    
        }
    
        // A synthetic class just to obtain the command field
        // Gson cannot instantiate abstract classes like what AbstractCommandDto is 
        private static final class CommandProbingDto
                extends AbstractCommandDto {
        }
    
    }
    

    以及如何使用:

    public static void main(final String... args) {
        // Build a command DTO-aware Gson instance
        final Gson gson = new GsonBuilder()
                .registerTypeAdapterFactory(getAbstractCommandDtoTypeAdapterFactory())
                .create();
        // Build command registry
        final Map<Class<?>, Consumer<?>> commandRegistry = new LinkedHashMap<>();
        commandRegistry.put(HelloCommandDto.class, new HelloCommand());
        // Simulate and accept a request
        final AbstractCommandDto abstractCommandDto = gson.fromJson("{\"command\":\"hello\",\"name\":\"Welt\"}", AbstractCommandDto.class);
        // Resolve a command
        final Consumer<?> command = commandRegistry.get(abstractCommandDto.getClass());
        if ( command == null ) {
            throw new IllegalArgumentException("Cannot handle " + abstractCommandDto.command);
        }
        // Dispatch
        @SuppressWarnings("unchecked")
        final Consumer<AbstractCommandDto> castCommand = (Consumer<AbstractCommandDto>) command;
        castCommand.accept(abstractCommandDto);
        // Simulate a response
        System.out.println(gson.toJson(abstractCommandDto));
    }
    
    private static final class HelloCommand
            implements Consumer<HelloCommandDto> {
    
        @Override
        public void accept(final HelloCommandDto helloCommandDto) {
            System.out.println("Hallo " + helloCommandDto.name);
        }
    
    }
    

    输出:

    你好世界

    【讨论】:

      猜你喜欢
      • 2022-01-12
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-15
      • 2011-08-03
      • 2012-07-27
      • 1970-01-01
      相关资源
      最近更新 更多