Custom serializer - deserializer using GSON for list BasicNameValuePairs

I am trying to implement my own gson serializer / deserializer for some list of BasicNameValuePair objects.

I saw the partial solution code (for serialization) here: How to get Gson to serialize a list of base pairs of name values?

However, I also wanted to implement deserialization , and I tried my chances, and the code is here:

package dto; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.message.BasicNameValuePair; import com.google.gson.TypeAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; 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(); } @Override public List<BasicNameValuePair> read(JsonReader in) throws IOException { ArrayList<BasicNameValuePair> list=new ArrayList<BasicNameValuePair>(); in.beginObject(); while (in.hasNext()) { String key = in.nextName(); String value = in.nextString(); list.add(new BasicNameValuePair(key,value)); } in.endObject(); return list; } } 

Code to initialize and populate the list

 ArrayList<BasicNameValuePair> postParameters=new ArrayList<BasicNameValuePair>(); postParameters.add(new BasicNameValuePair("some_key","some_value")); 

And here is the code to use the new KeyValuePairSerializer class:

  GsonBuilder gsonBuilder= new GsonBuilder(); gsonBuilder.registerTypeAdapter(KeyValuePairSerializer.class, new KeyValuePairSerializer()); Gson gson1=gsonBuilder.create(); //serialization works just fine in the next line String jsonUpdate=gson1.toJson(postParameters, KeyValuePairSerializer.class); ArrayList<BasicNameValuePair> postParameters2 = new ArrayList<BasicNameValuePair>(); //postParameters2 = gson1.fromJson(jsonUpdate, KeyValuePairSerializer.class); //? how to cast properly //deserialization throws an error, it can't cast from ArrayList<BasicNameValuePair> to KeyValuePairSerializer gson1.fromJson(jsonUpdate, KeyValuePairSerializer.class); 

The problem is that it throws an exception at the end, and I donโ€™t know where exactly the problem is, and still not sure how to write the last line to return the result to the new postParameters2 ArrayList.

+7
source share
4 answers

Adapted from the GSON Collection 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); 
+8
source

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

The only way to call the redefined KeyValuePairSerializer read function is to call: gson1.fromJson(jsonUpdate, KeyValuePairSerializer.class); without storing the result value in a variable. Although it will handle the function just fine, it will throw an error inside the gson class, because it will not be able to drop from ArrayList into KeyValuePairSerializer. And I understand why (erasing, I think), I just donโ€™t know how to do it properly.

In any case, I found a workaround to solve this problem. It seems like instead of registering a 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 from deserializing with something simpler :

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

Both JsonObject and NameValuePair behave similarly to dictionaries, I donโ€™t think you need to convert them to another if the use case is similar. In addition, JsonObject allows you to process your values โ€‹โ€‹more efficiently (instead of iterating over an array of value pairs to find the key you need to get, JsonObject behaves the same way as Map so that you can directly call the key name and it will return the desired property) :

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

In your case, I will create a JsonObject from a string, response or stream, and then get it as a map (as shown above):

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

I have been following this blog for GSON Collection Examples . The link is easy to understand and implement.

 public class TimeSerializer implements JsonSerializer<time> { /** * Implementing the interface JsonSerializer. * Notice that the the interface has a generic * type associated with it. * Because of this we do not have ugly casts in our code. * {@inheritDoc} */ public JsonElement serialize( final Time time, final Type type, final JsonSerializationContext jsonSerializationContext) { /** * Returning the reference of JsonPremitive * which is nothing but a JSONString. * with value in the format "HH:MM" */ return new JsonPrimitive(String.format("%1$02d:%2$02d", time.getHour(), time.getMinute())); } 
-one
source

All Articles