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"}]}"
我发现这个工作的唯一方法是使用
public JsonElement perro;
Basically speaking, You need to create a custom gson TypeAdapter
class and write the conversion login from Object to String yourself.
Then annotate the field indicating what TypeAdapter to use in order to read/write it using gson.
More details in this blog post: Gson TypeAdapter Example
Example: Prasing class object as a raw JSON string
public class StringTypeAdapter extends TypeAdapter<String> {
@Override
public void write(JsonWriter out, String value) throws IOException {
try {
JSONObject jsonObject = new JSONObject(value);
out.beginObject();
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
String keyValue = jsonObject.getString(key);
out.name(key).value(keyValue);
}
out.endObject();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public String read(JsonReader in) throws IOException {
in.beginObject();
JSONObject jsonObject = new JSONObject();
while (in.hasNext()) {
final String name = in.nextName();
final String value = in.nextString();
try {
jsonObject.put(name, value);
} catch (JSONException e) {
e.printStackTrace();
}
}
in.endObject();
return jsonObject.toString();
}
}
Using the TypeAdapter:
@JsonAdapter(StringTypeAdapter.class)
private String someClass; // Lazy parsing this json
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
You should be able to use public JsonObject perro;
You can then call gson.toJson(perro)
to get the String
value.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.