Java-使用Gson序列化Iterable <map.entry <>>

时间:2019-03-24 14:27:20

标签: java serialization gson entryset

我尝试使用Google 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

1 个答案:

答案 0 :(得分:1)

一种更清洁的方法是

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

enter image description here

没有自定义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())

收益true,并返回空的boundFields LinkedHashMap
因此,这里

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

不执行循环,并且没有提取和写入值

boundField.write(...)