代码设计:JSON 从 Socket 到自定义处理程序 class

Code Design: JSON from Socket to custom handler class

我在 Java 中有一个套接字服务器。此套接字将接收具有特定结构的 json-strings。

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

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

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

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

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

class BaseCommand {
    public CommandType command;
}

class TestCommand extends BaseCommand {
    public String name;
}

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

我声明了一个 ENUM 来将命令类型映射到处理程序:

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);
}

现在我有了命令类型枚举,通过 Google Guices 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);
}

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

此致,迈克尔

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

您可以使用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);
    }

}

输出:

Hallo Welt