2017-10-17 60 views
0

Gson類可以包含JSONObject類型的字段嗎? 這裏是我GSON類GSON類中的JSONObject字段 - 仍爲空

class Item { 
    @Expose 
    var name: String? = "" 
    @Expose 
    var type: String? = "" 
    @Expose 
    @SerializedName("agr") 
    var aggregate: JSONObject? = null 
    @Expose 
    @SerializedName("seg") 
    var segments: JSONObject? = null 
    @Expose 
    @SerializedName("ts") 
    var timestamp: String? = "" 
} 

的JSONObject的領域仍然連載時(使用默認改造GsonConverterFactory)一個空的JSONObject。這是我得到的。任何建議讓它寫?

{"items":[{"agr":{},"name":"Logged In","seg":{},"ts":"2017-10-17T12:20:32Z","type":"event"}]} 
+0

你需要一個自定義的反序列化器,你可以在這裏找到更多的信息:https://stackoverflow.com/questions/16590377/custom-json-deserializer-using-gson – Jibbo

回答

0

一個解決 - 一個HashMap的更換的JSONObject()有幫助我取得了同樣的結果。

0

1.You可以簡單地改寫這個類,希望能幫助你:

public class GsonConverterFactory extends Converter.Factory { 
/** 
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and 
* decoding from JSON (when no charset is specified by a header) will use UTF-8. 
*/ 
public static GsonConverterFactory create() { 
    return create(new Gson()); 
} 
/** 
* Create an instance using {@code gson} for conversion. Encoding to JSON and 
* decoding from JSON (when no charset is specified by a header) will use UTF-8. 
*/ 
public static GsonConverterFactory create(Gson gson) { 
    return new GsonConverterFactory(gson); 
} 
private final Gson gson; 
private GsonConverterFactory(Gson gson) { 
    if (gson == null) throw new NullPointerException("gson == null"); 
    this.gson = gson; 
} 
@Override 
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, 
                 Retrofit retrofit) { 
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)).nullSafe(); 
    return new GsonResponseBodyConverter<>(gson, adapter); 
} 
@Override 
public Converter<?, RequestBody> requestBodyConverter(Type type, 
                 Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { 
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type)).nullSafe(); 
    return new GsonRequestBodyConverter<>(gson, adapter); 
} 

}