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

前端 未结 1 1452
长情又很酷
长情又很酷 2021-01-16 11:16

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

ArrayList kvp=new ArrayList

        
1条回答
  •  醉话见心
    2021-01-16 11:29

    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> {
    @Override
    public void write(JsonWriter out, List data) throws IOException {
        out.beginObject();
        for(int i=0; i 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));
    

    0 讨论(0)
提交回复
热议问题