我试图用google库序列化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
发布于 2019-03-24 14:38:00
一个更干净的方法可能是
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将输入Entry (Class<?> raw参数)识别为
interface Map.Entry<K, V> { ... }因此
if (raw.isInterface())产生true,然后返回一个空的boundFields LinkedHashMap。
因此,在这里
for (BoundField boundField : boundFields.values()) { ... }没有执行循环,也没有提取和写入任何值
boundField.write(...)https://stackoverflow.com/questions/55324814
复制相似问题