[英]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. 在Java中使用GSON是否有任何注释,我可以指示一个字段,即使它是一个对象,它应该将它保持为原始字符串。 ?
?
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. 基本上,您需要创建一个自定义的gson
TypeAdapter
类,并自己编写从Object到String的转换登录。
Then annotate the field indicating what TypeAdapter to use in order to read/write it using gson. 然后注释该字段,指示要使用哪个TypeAdapter以使用gson读取/写入它。
More details in this blog post: Gson TypeAdapter Example 此博客文章中的更多详细信息: Gson TypeAdapter示例
Example: Prasing class object as a raw JSON string 示例:将类对象作为原始JSON字符串进行打包
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: 使用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: 根据@ mrsegev的回答,这里有一个更简单的版本(在Kotlin中),适用于任意对象:
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 这利用了https://github.com/google/gson/pull/667中添加的
JsonWriter#jsonValue()
Usage: 用法:
@JsonAdapter(RawJsonAdapter::class)
val fieldName: String? = null
You should be able to use public JsonObject perro;
你应该能够使用
public JsonObject perro;
You can then call gson.toJson(perro)
to get the String
value. 然后,您可以调用
gson.toJson(perro)
来获取String
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.