【问题标题】:Gson custom byte[] handlerGson 自定义字节 [] 处理程序
【发布时间】:2017-04-30 10:40:35
【问题描述】:

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

但是,当我运行 test() 代码时,它仍保留在 B64 中并且不会返回到 byte[]。

如何解决?

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: ["hello","d29ybGQ\u003d"]
from: [hello, d29ybGQ=]
i: 0    class: class java.lang.String   value: hello
i: 1    class: class java.lang.String   value: d29ybGQ= //this should be in byte[].class

【问题讨论】:

  • ProcessBuilder.Redirect.Type 的重载是没有用的。是不是笔误?
  • Netbeans 说必须覆盖,所以我做到了。

标签: java serialization gson


【解决方案1】:

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

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

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

【讨论】:

  • 所以我不能把所有东西都放到一个通用的Container中然后再转回byte[]?
  • 当然,但是 1) 您需要使用适当的通用容器,例如List&lt;byte[]&gt;,不仅仅是原始的List(无论如何你都不应该使用它); 2) 使用TypeTokens:futurestud.io/tutorials/…进行反序列化时仍然需要提供这些信息。
猜你喜欢
  • 2013-02-12
  • 2011-05-04
  • 1970-01-01
  • 1970-01-01
  • 2011-07-27
  • 2017-12-18
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多