RuntimeException in Gson parsing JSON: Failed to invoke protected java.lang.ClassLoader() with no args
The problem is you're attempting to just straight convert a system-provided class (Location
) to JSON. And, as you see you run into problems with serializing internal state / Java specific things. JSON is meant as a semi-generic way to pass information around.
You can't use the @Expose
annotation easily because it's not your class; that would require modifying the source code for Location
or via a fairly extensive process of adding them at runtime using jassist (see: http://ayoubelabbassi.blogspot.com/2011/01/how-to-add-annotations-at-runtime-to.html)
Looking at the Location
class, I'd simply create a custom Gson Serializer and Deserializer and be done with it. What you're actually interested in is the GPS data, not internals of the class itself. You just construct the JSON containing the information you need in the serializer using the getters, then in the Deserializer you create a new instance of Location
and populate it with the information from the supplied JSON using the public setters.
class LocationSerializer implements JsonSerializer<Location>
{
public JsonElement serialize(Location t, Type type,
JsonSerializationContext jsc)
{
JsonObject jo = new JsonObject();
jo.addProperty("mProvider", t.getProvider());
jo.addProperty("mAccuracy", t.getAccuracy());
// etc for all the publicly available getters
// for the information you're interested in
// ...
return jo;
}
}
class LocationDeserializer implements JsonDeserializer<Location>
{
public Location deserialize(JsonElement je, Type type,
JsonDeserializationContext jdc)
throws JsonParseException
{
JsonObject jo = je.getAsJsonObject();
Location l = new Location(jo.getAsJsonPrimitive("mProvider").getAsString());
l.setAccuracy(jo.getAsJsonPrimitive("mAccuracy").getAsFloat());
// etc, getting and setting all the data
return l;
}
}
Now in your code you use GsonBuilder
and register the classes:
...
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Location.class, new LocationDeserializer());
gsonBuilder.registerTypeAdapter(Location.class, new LocationSerializer());
Gson gson = gsonBuilder.create();
...
That should pretty much take care of it.
Consider to create a custom Object that models your GSON, parsing the content Object per Object and field per field
something like
JSONObject lastKnownLocation = obj.getJSONObject("lastKnownLocation");
JSONArray mResults = lastKnownLocation.getJSONArray("mResults");
etc...
MyGSON mg=new MyGSON(lastKnownLocation, mResults etc....);
So you can obtain the full control of the parsing, and adding a try\catch block in the critical mExtra part you can exclude the block, or manage the exception as you want, easily.