Gson serialize a list of polymorphic objects

There’s a simple solution: Gson’s RuntimeTypeAdapterFactory (from com.google.code.gson:gson-extras:$gsonVersion). You don’t have to write any serializer, this class does all work for you. Try this with your code: ObixBaseObj lobbyObj = new ObixBaseObj(); lobbyObj.setIs(“obix:Lobby”); ObixOp batchOp = new ObixOp(); batchOp.setName(“batch”); batchOp.setIn(“obix:BatchIn”); batchOp.setOut(“obix:BatchOut”); lobbyObj.addChild(batchOp); RuntimeTypeAdapterFactory<ObixBaseObj> adapter = RuntimeTypeAdapterFactory .of(ObixBaseObj.class) .registerSubtype(ObixBaseObj.class) .registerSubtype(ObixOp.class); Gson gson2=new GsonBuilder().setPrettyPrinting().registerTypeAdapterFactory(adapter).create(); Gson gson = … Read more

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this: { “dstOffset” : 3600, “rawOffset” : 36000, “status” : “OK”, “timeZoneId” : “Australia/Hobart”, “timeZoneName” : “Australian Eastern Daylight Time” } You’re telling Gson that you have an array of Post objects: List<Post> postsList = Arrays.asList(gson.fromJson(reader, Post[].class)); You don’t. The JSON represents exactly one Post … Read more

Using Gson in Kotlin to parse JSON array

You need to change parameter in your fromJson() function call like following: val weatherList: List<WeatherObject> = gson.fromJson(stringReader , Array<WeatherObject>::class.java).toList() You need to pass Array<WeatherObject>::class.java for class type and then convert result into List. No need to change registerTypeAdapter() function call. Check following code: fun getWeatherObjectFromJson(jsonStr: String): List<WeatherObject> { var stringReader: StringReader = StringReader(jsonStr) var jsonReader: … Read more

Reading value of nested key in JSON with Java (Jackson)

With Jackson’s tree model (JsonNode), you have both “literal” accessor methods (‘get’), which returns null for missing value, and “safe” accessors (‘path’), which allow you to traverse “missing” nodes. So, for example: JsonNode root = mapper.readTree(inputSource); int h = root.path(“response”).path(“history”).getValueAsInt(); which would return the value at given path, or, if path is missing, 0 (default … Read more

How to keep fields sequence in Gson serialization

You’d need to create a custom JSON serializer. E.g. public class FooJsonSerializer implements JsonSerializer<Foo> { @Override public JsonElement serialize(Foo foo, Type type, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.add(“bar”, context.serialize(foo.getBar()); object.add(“baz”, context.serialize(foo.getBaz()); // … return object; } } and use it as follows: Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class, new FooJsonSerializer()).create(); String json = … Read more

Query a JSONObject in java

I’ve just unexpectedly found very interesting project: JSON Path JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. With this library you can do what you are requesting even easier, then my previous suggestion: String hello = JsonPath.read(json, “$.data.data2.value”); System.out.println(hello); //prints hello Hope this might … Read more

Does it make sense to use reflection when implementing toString()?

Yes. It’s OK to use GSON/Jackson/Reflections library to implement toString() method. There are few ways to implement toString method. Reflections (Apache library) @Override public String toString(){ return org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(this); } JSON based implementation (GSON, Jackson libraries) // GSON library for JSON @Override public String toString(){ return new com.google.gson.Gson().toJson(this); } // Jackson libabry for JSON/YAML @Override public … Read more

Serialize Java 8 LocalDate as yyyy-mm-dd with Gson

Until further notice, I have implemented a custom serializer like so: class LocalDateAdapter implements JsonSerializer<LocalDate> { public JsonElement serialize(LocalDate date, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(date.format(DateTimeFormatter.ISO_LOCAL_DATE)); // “yyyy-mm-dd” } } It can be installed e.g. like so: Gson gson = new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(LocalDate.class, new LocalDateAdapter()) .create();

GSON issue with String

The = sign is encoded to \u003d. Hence you need to use disableHtmlEscaping(). You can use Gson gson = new GsonBuilder().disableHtmlEscaping().create(); String s2 = gson.toJson(hm.toString()); For \/ turning into \\/ issue, the solution is s2.replace(“\\\\”, “\\”);

Gson handle object or array

I came up with an answer. private static class MyOtherClassTypeAdapter implements JsonDeserializer<List<MyOtherClass>> { public List<MyOtherClass> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) { List<MyOtherClass> vals = new ArrayList<MyOtherClass>(); if (json.isJsonArray()) { for (JsonElement e : json.getAsJsonArray()) { vals.add((MyOtherClass) ctx.deserialize(e, MyOtherClass.class)); } } else if (json.isJsonObject()) { vals.add((MyOtherClass) ctx.deserialize(json, MyOtherClass.class)); } else { throw new RuntimeException(“Unexpected JSON … Read more

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