I need a little help on GSON parsing of nested classes

I am trying to deserialize some JSON data received from the bridge binding that I am working on. Its JSON data structure is as follows…

{"devices":[
	{
		"CURRENT_TEMPERATURE":"255.255",
		"STAT_MODE":
			{
			"MANUAL_OFF":true,
			"TIMECLOCK":true
			},
		"TIMER":false,
		"device":"Watering System"
	}
]}

I am trying to parse it with GSON @SerializedName annotations. The code is shown below. The problem lies with the deep nesting of the JSON structure resp. the Java classes. To be specific with the inner-inner class StatMode. When I run the createJsonResponse method, it does not throw any exceptions, but when I try to access the StatMode class via its property getter (not shown), it causes a crash.

I think the parsing is working, but I don’t know if the classes are being created correctly, or how to access them. I think it could be due to the static keywords perhaps??

class JsonResponse {
	@SerializedName("devices")
	private List<DeviceInfo> deviceInfos;

	static class DeviceInfo {
		@SerializedName("device")
		private String deviceName;
		@SerializedName("CURRENT_TEMPERATURE")
		private BigDecimal currentTemperature;
		@SerializedName("TIMER")
		private Boolean timerOn;
		@SerializedName("STAT_MODE")
		private StatMode statMode;

		static class StatMode {
			@SerializedName("MANUAL_OFF")
			private Boolean manualoff;
			@SerializedName("TIMECLOCK")
			private Boolean thermostat;
			// property getter methods..
		}            
		// property getter methods..
        }
	// property getter methods..

	static @Nullable JsonResponse createJsonResponse(String response) {
	        try {
			Gson gson = new Gson();
			return gson.fromJson(response, JsonResponse.class);
        	} catch (Exception e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}
}

Why not? Check.

Also, why have your classes be static in the first place?

You are right (mea culpa). The problems was not with the GSON deserialization code, but rather with the JSON payload: sometimes the payload was missing a certain field which was causing a null variable, which caused the crash :wink:

The Gson User Guide explains why that is important:

Nested Classes (including Inner Classes)

Gson can serialize static nested classes quite easily.

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it.

1 Like

Yup. Thats why I used static nested classes. :slight_smile: