Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using GSON do not parse a field, only keep it with the json raw string

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"}]}"
like image 357
Kenenisa Bekele Avatar asked Jun 29 '17 17:06

Kenenisa Bekele


Video Answer


2 Answers

The only way I found this to work was using

public JsonElement perro;
like image 113
Kenenisa Bekele Avatar answered Oct 10 '22 19:10

Kenenisa Bekele


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
like image 45
tmm1 Avatar answered Oct 10 '22 17:10

tmm1