android - 我如何让 Gson 序列化基本名称值对列表?

标签 android json serialization gson key-value

我正在尝试使用类型适配器和 Gson 序列化 BasicNameValuePairs 列表

ArrayList<BasicNameValuePair> kvp=new ArrayList<BasicNameValuePair>();
kvp.add(new BasicNameValuePair("car","ferrari"));
kvp.add(new BasicNameValuePair("speed","fast"));

这就是我想要的结果

{"car":"ferrari","speed":"fast"}

而不是这个

[{"name":"car","value":"ferrari"},{"name":"speed","value":"fast"}]

最佳答案

要根据规范对其进行序列化,您需要制作一个自定义类型适配器来处理通用列表。首先创建将对输出进行正确格式化的类。

public class KeyValuePairSerializer extends TypeAdapter<List<BasicNameValuePair>> {
@Override
public void write(JsonWriter out, List<BasicNameValuePair> data) throws IOException {
    out.beginObject();
    for(int i=0; i<data.size();i++){
        out.name(data.get(i).getName());
        out.value(data.get(i).getValue());
    }
    out.endObject();
}
/*I only need Serialization*/
@Override
public List<BasicNameValuePair> read(JsonReader in) throws IOException {
    return null;
}
}

然后使用自定义 Gson 构建器来使用该类型适配器来创建正确的 JSON 字符串。

    GsonBuilder gsonBuilder= new GsonBuilder();
    gsonBuilder.registerTypeAdapter(KeyValuePairSerializer.class, new KeyValuePairSerializer());
    Gson gson=gsonBuilder.create();
    Logger.e(getClass().getSimpleName(),gson.toJson(kvp, KeyValuePairSerializer.class));

关于android - 我如何让 Gson 序列化基本名称值对列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12521816/

相关文章:

android - logback-android 是否支持 DBAppender?

android - 将触摸区域限制为 libgdx 中的纹理区域

android - 使用 OKHTTP3 向 Web 服务器发送 POST 请求

php - 查询多个 MySQL 表并将数据编码为 JSON

python |如何从 AWS 响应的结果中解析 JSON?

ios - JSON POST Web 服务中的多个 Json 对象和 3 个字符串

c++ - C++应用程序中数据结构的崩溃恢复

c# - 从 Web Api 返回 XML

java - 串口版uid和eclipse

android - GCM BroadcastReceiver 仅在应用程序正在运行或在后台运行时触发