Gson class nested parameters have no value

I have a problem parsing strings for nested classes. This is my json line:

[
 {
  "DeviceName":"devtest",
  "StolenFlag":false,
  "BatteryLevel":2,
  "LastLocalization":{
     "Geography":{
        "CoordinateSystemId":4326,
        "WellKnownText":"POINT (52.403371 16.955098)"
         }
      }
 },
 {
  "DeviceName":"testdev2",
  "StolenFlag":false,
  "BatteryLevel":2,
  "LastLocalization":{
     "Geography":{
        "CoordinateSystemId":4326,
        "WellKnownText":"POINT (16.955098 52.403371)"
         }
      }
 }
]

My classes:

class Geography implements Parcelable{
    @SerializedName("CoordinateSystemId")
public int CoordinateSystemId;

@SerializedName("WellKnownText")
public String WellKnownText;
....
}

class MyDevice implements Parcelable{
    @SerializedName("DeviceName")
    public String DeviceName;

    @SerializedName("StolenFlag")
    public Boolean StolenFlag;

    @SerializedName("BatteryLevel")
    public int BatteryLevel;


    @SerializedName("LastLocalization")
    public Geography LastLocalization;

    ...
}

And code conversion:

Gson gson = new Gson();
            List<MyDevice> MyDev = gson.fromJson(result, new TypeToken<List<MyDevice>>() {
            }.getType());

Since the device parameters are being converted correctly, I get null / 0 values ​​in the Geography object inside the device. Do you have any idea why?

I get a list with Devices, each of which contains a geography object. The parameters of this object are null / 0. I hope you understand.

@EDIT @

I changed public Geography LastLocalization; in public Map<String, Geography> LastLocalization;

And it works fine, but got an error in the writeToParcel method. Any ideas how to fix this?

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(DeviceName);
        dest.writeByte((byte) (StolenFlag ? 1 : 0));
        dest.writeInt(BatteryLevel);
        dest.writeParcelable(LastLocalization, 0);
    }
}
+4
source share
1 answer
@SerializedName("LastLocalization")
public Geography LastLocalization;

Gson, LastLocalization, LastLocalization.

, LastLocalization, Geography.

Gson LastLocalization JSON, , LastLocalization, Geography . , - . JSON LastLocalization java Geography, Java.

, , Gson , JSON Java-, Java - JSON.

+1

Source: https://habr.com/ru/post/1629827/


All Articles