Custom serializer - deserializer using GSON for a list of BasicNameValuePairs Custom serializer - deserializer using GSON for a list of BasicNameValuePairs json json

Custom serializer - deserializer using GSON for a list of BasicNameValuePairs


Adapted from the GSON Collections Examples:

GsonBuilder gsonBuilder= new GsonBuilder();gsonBuilder.registerTypeAdapter(KeyValuePairSerializer.class, new KeyValuePairSerializer());Gson gson1=gsonBuilder.create();Type collectionType = new TypeToken<ArrayList<BasicNameValuePair>>(){}.getType();ArrayList<BasicNameValuePair> postParameters2 = gson1.fromJson(jsonUpdate, collectionType);


registerTypeAdapter seems to work only for the serializer not for deserializer.

The only way to call the overridden read function of the KeyValuePairSerializer is to call the:gson1.fromJson(jsonUpdate, KeyValuePairSerializer.class); without saving the result value in a variable. While it will process the function just fine, it will throw an error inside gson class because it will not be able to cast from the ArrayList to the KeyValuePairSerializer. And I kinda understand why (erasure I guess), just don't know how to do it properly.

Anyway I found a workaround to solve this issue.It seems that instead of registering the gson object and calling registerTypeAdapter and then using gson1.toJson(Object src, Type typeOfSrc) and gson1.fromJson(String json,Class <T> classOfT) I can get away for deserialization with something simpler like:

KeyValuePairSerializer k= new KeyValuePairSerializer();parametersList = (ArrayList<BasicNameValuePair>)k.fromJson(jsonUpdate);


Both JsonObject's and NameValuePair's behave in a similar way to dictionaries, I don't think you need to convert one into the other if the use case is similar. Additionally JsonObject allows you to treat your values even easier (instead of looping through the array of value pairs to find the key you need to get its value, JsonObject behaves similarly to a Map in a way that you can directly call the name of the key and it'll return the desired property):

jsonObject.get("your key").getAsString(); (getAsBoolean(), getAsInt(), etc).

For your case I'd create a JsonObject from your string, response or stream and then access it as a map (as shown above):

JsonParser parser = new JsonParser();JsonObject o = (JsonObject)parser.parse("your json string");