Gson: Is there an easier way to serialize a map

Only the TypeToken part is neccesary (when there are Generics involved). Map<String, String> myMap = new HashMap<String, String>(); myMap.put(“one”, “hello”); myMap.put(“two”, “world”); Gson gson = new GsonBuilder().create(); String json = gson.toJson(myMap); System.out.println(json); Type typeOfHashMap = new TypeToken<Map<String, String>>() { }.getType(); Map<String, String> newMap = gson.fromJson(json, typeOfHashMap); // This type must match TypeToken System.out.println(newMap.get(“one”)); System.out.println(newMap.get(“two”)); Output: … Read more

Gson optional and required fields

As you note, Gson has no facility to define a “required field” and you’ll just get null in your deserialized object if something is missing in the JSON. Here’s a re-usable deserializer and annotation that will do this. The limitation is that if the POJO required a custom deserializer as-is, you’d have to go a … Read more

Trouble with Gson serializing an ArrayList of POJO’s

You need to give Gson information on the specific generic type of List you’re using (or any generic type you use with it). Particularly when deserializing JSON, it needs that information to be able to determine what type of object it should deserialize each array element to. Type listOfTestObject = new TypeToken<List<TestObject>>(){}.getType(); String s = … Read more

gson throws MalformedJsonException

I suspect that result1 has some characters at the end of it that you can’t see in the debugger that follow the closing } character. What’s the length of result1 versus result2? I’ll note that result2 as you’ve quoted it has 169 characters. GSON throws that particular error when there’s extra characters after the end … Read more

“Unparseable date: 1302828677828” trying to deserialize with Gson a millisecond-format date received from server

Alfonso’s comment: Finally I got the solution: // Creates the json object which will manage the information received GsonBuilder builder = new GsonBuilder(); // Register an adapter to manage the date types as long values builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return new Date(json.getAsJsonPrimitive().getAsLong()); } }); … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)