![](/img/trans.png)
[英]Java Gson JSON: Serializing an Object which contains a List<Map.Entry<...,...>>
[英]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 將輸入Entry
( Class<?> 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.