Java Gson自定义字节[]处理程序

Java Gson自定义字节[]处理程序,java,serialization,gson,Java,Serialization,Gson,我想将byte[].class转换为JSON到B64。这已通过自定义适配器完成 但是,当我运行测试代码时,它仍保留在B64中,并且不会返回到字节[] 如何修复它 public static final Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()).create(); static class ByteArrayToBase6

我想将byte[].class转换为JSON到B64。这已通过自定义适配器完成

但是,当我运行测试代码时,它仍保留在B64中,并且不会返回到字节[]

如何修复它

public static final Gson gson = new GsonBuilder().registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter()).create();

static class ByteArrayToBase64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> {

    public byte[] deserialize(JsonElement json, ProcessBuilder.Redirect.Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return Util.fromBase64(json.getAsString());
    }

    public JsonElement serialize(byte[] src, ProcessBuilder.Redirect.Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(Util.toBase64(src));
    }

    @Override
    public JsonElement serialize(byte[] src, java.lang.reflect.Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(Util.toBase64(src));
    }

    @Override
    public byte[] deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        return Util.fromBase64(json.getAsString());
    }
}



private static void test(){
    ArrayList test = new ArrayList();
    test.add("hello");
    test.add("world".getBytes());

    final String json = Gson.gson.toJson(test);

    System.out.println("json: " + json);

    ArrayList from = Gson.gson.fromJson(json, ArrayList.class);
    System.out.println("from: " + from);
    for(int i = 0; i < from.size(); i++){
        System.out.println("i: " + i + "\tclass: " + from.get(i).getClass() + "\tvalue: " + from.get(i));
    }
}

它如何知道这个特定的JSON字符串恰好来自一个字节[]?您需要在解码时指定它,例如

final byte[] bytes = "world".getBytes();
final String json = Gson.gson.toJson(bytes);
final byte[] bytes1 = Gson.gson.fromJson(json, byte[].class);

或者有一个带有byte[]字段的类。

所以我不能将所有内容都放在一个通用容器中,然后将其返回到byte[]?当然,但是1您需要使用一个合适的通用容器,例如List,而不仅仅是raw List,您无论如何都不应该使用它;2在使用TypeTokens进行反序列化时,仍然需要提供以下信息:。ProcessBuilder.Redirect.Type的重载无效。这是一个输入错误吗?Netbeans说必须覆盖,所以我做了。
final byte[] bytes = "world".getBytes();
final String json = Gson.gson.toJson(bytes);
final byte[] bytes1 = Gson.gson.fromJson(json, byte[].class);