How do I get Gson to serialize a list of basic name value pairs?

最后都变了- 提交于 2019-12-01 09:54:19

问题


I'm trying to serialize a list of BasicNameValuePairs using type adapters and Gson

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

this is the result I want

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

instead of this

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

回答1:


To serialize this according to specification you need to make a custom type adapter that will handle the generic list. First create the class that will do the proper formatting on the output.

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;
}
}

Then use a custom Gson builder to use that type adapter to create the proper JSON string.

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


来源:https://stackoverflow.com/questions/12521816/how-do-i-get-gson-to-serialize-a-list-of-basic-name-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!