繁体   English   中英

Java - 序列化可迭代<Map.Entry<> &gt; 与 Gson

[英]Java - Serializing Iterable<Map.Entry<>> with Gson

我试图用谷歌 GSON 库从类型 Map.Entry 序列化一个“Iterable” - 我得到了一个空输出。

这里是代码示例:

static private Iterable<Map.Entry<String, Integer>> getIterable(){
    HashMap<String, Integer> map = new HashMap<>();
    map.put("1", 1);
    map.put("2", 2);

    Iterable<Map.Entry<String, Integer>> iterable = map.entrySet();
    return  iterable;

}

public static void main(String[] args) {

    Iterable<Map.Entry<String, Integer>> myIterable = getIterable();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.enableComplexMapKeySerialization().create();
    String  a= gson.toJson(myIterable);
    System.out.println(a);

}

这是输出:

[{},{}]

知道我做错了什么吗?

谢谢 :)

Java 版本:1.8
gson 版本:2.6.2

更清洁的方法可能是

final Iterable<Entry<String, Integer>> iterable = getIterable();
final Gson gson = new Gson();
final JsonArray jsonArray = new JsonArray();

for (final Entry<String, Integer> entry : iterable) {
    final JsonElement jsonElement = gson.toJsonTree(entry);
    jsonElement.getAsJsonObject().remove("hash");
    jsonArray.add(jsonElement);
}

或者我喜欢的Stream版本

StreamSupport.stream(iterable.spliterator(), false)
             .map(gson::toJsonTree)
             .map(JsonElement::getAsJsonObject)
             .peek(obj -> obj.remove("hash"))
             .collect(of(
                     JsonArray::new,
                     (array, obj) -> array.add(obj),
                     (output, toMerge) -> {
                         output.addAll(toMerge);
                         return output;
                     }
             ));

输出: [{"key":"1","value":1},{"key":"2","value":2}]


TL;DR :您需要一个自定义TypeAdapterFactory一个自定义TypeAdapter

请参阅TypeAdapters此方法

public static <TT> TypeAdapterFactory newFactory(
    final TypeToken<TT> type, final TypeAdapter<TT> typeAdapter) {
  return new TypeAdapterFactory() {
    @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal
    @Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
      return typeToken.equals(type) ? (TypeAdapter<T>) typeAdapter : null;
    }
  };
}

在此处输入图片说明

没有自定义TypeAdapterFactory

typeToken.equals(type)

返回false ,甚至不使用自定义TypeAdapter<Entry>


问题出在这里,在ReflectiveTypeAdapterFactory#write

@Override public void write(JsonWriter out, T value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }

  out.beginObject();
  try {
    for (BoundField boundField : boundFields.values()) {
      if (boundField.writeField(value)) {
        out.name(boundField.name);
        boundField.write(out, value);
      }
    }
  } catch (IllegalAccessException e) {
    throw new AssertionError(e);
  }
  out.endObject();
}

并在ReflectiveTypeAdapterFactory#getBoundFields

private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) {
  Map<String, BoundField> result = new LinkedHashMap<String, BoundField>();

  if (raw.isInterface()) {
    return result;
  }

Gson 将输入EntryClass<?> raw参数)识别为

interface Map.Entry<K, V> { ... }

所以

if (raw.isInterface())

yield true ,并返回一个空的boundFields LinkedHashMap
因此,这里

for (BoundField boundField : boundFields.values()) { ... }

不执行循环,也没有提取和写入任何值

boundField.write(...)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM