7

在 Java 中使用 GSON 是否有任何注释,我可以在其中指示一个字段,即使它是一个对象,它也应该将其保留为原始字符串。?

或者实现这一目标的最简单方法是什么?

//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"}]}"
4

4 回答 4

16

我发现这个工作的唯一方法是使用

public JsonElement perro;
于 2017-08-04T02:18:33.890 回答
4

根据@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()
    }
}

这利用了JsonWriter#jsonValue()https://github.com/google/gson/pull/667中添加的

用法:

@JsonAdapter(RawJsonAdapter::class)
val fieldName: String? = null
于 2018-05-25T21:24:33.220 回答
2

基本上,您需要创建一个自定义的 gsonTypeAdapter类并自己编写从 Object 到 String 的转换登录。

然后注释指示要使用什么 TypeAdapter 的字段,以便使用 gson 读取/写入它。

此博客文章中的更多详细信息:Gson TypeAdapter 示例

示例:将类对象转换为原始 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();
    }
}

使用类型适配器:

@JsonAdapter(StringTypeAdapter.class)
private String someClass; // Lazy parsing this json
于 2017-06-29T18:13:18.010 回答
0

你应该可以使用public JsonObject perro;

然后,您可以调用gson.toJson(perro)以获取String值。

于 2017-06-29T17:31:55.590 回答