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.
Arise
source share