gpt4 book ai didi

java - 代码设计 : JSON from Socket to custom handler class

转载 作者:行者123 更新时间:2023-11-30 10:32:43 26 4
gpt4 key购买 nike

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

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

我不能改变这个结构。 “command”的值将声明内容的类型。

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

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

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

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

class BaseCommand {
public CommandType command;
}

class TestCommand extends BaseCommand {
public String name;
}

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

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

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

public final Class<? extends CommandHandler> handlerClass;

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

我的处理程序正在实现此接口(interface):

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

现在我有了命令类型 enum 并通过 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() 方法委托(delegate)给另一个支持 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

关于java - 代码设计 : JSON from Socket to custom handler class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com