Using GSON in Java is there any annotation where I can indicate a field that it should keep it as a raw string even though it is an object. ?
Or What would be the easiest way to achieve this?
//This is the original
@SerializedName("perro")
public Perro perro
//This is what I want to achieve
@SerializedName("perro")
public String perro
So the result should be
perro = "{"Users":[{"Name":"firulais","Raza":"beagle"},{"Name":"Spike","Value":"Terrier"}]}"
The only way I found this to work was using
public JsonElement perro;
Based on @mrsegev's answer, here's a simpler version (in Kotlin) that works with arbitrary objects:
class RawJsonAdapter: TypeAdapter<String>() {
override fun write(out: JsonWriter?, value: String?) {
out?.jsonValue(value)
}
override fun read(reader: JsonReader?): String {
return JsonParser().parse(reader).toString()
}
}
This takes advantage of JsonWriter#jsonValue()
which was added in https://github.com/google/gson/pull/667
Usage:
@JsonAdapter(RawJsonAdapter::class)
val fieldName: String? = null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With