Can I access the inner JSON layer using GSON with SerializedName

Say there is a JSON like this

{
  "data" : {
    "messages" : {
      "count" : 2,
      "data" : [
        "message 1",
        "message 2"
      ]
    },
    "user" : {
      "f_name" : "Mark",
      "l_name" : "lewis"
    },
    "city" : "London",
    "address" : "221b Baker Street, London"
  }
}

Can I achieve something like this with GSON?

public class JSData {
    public String city;
    public String address;
    public Array messages;
    @SerializedName("user.f_name")
    public String firstName;
    @SerializedName("user.l_name")
    public String lastName;
}

I want to access user.f_namedirectly, so I don’t need to create a wrapper for userand directly convert it using

 JSData topic = gson.fromJson(jsonObj, JSData.class);
+4
source share
2 answers

I think you should create a User like this class

    public class User {
        @SerializedName("f_name")
        public String firstName;

        @SerializedName("l_name")
        public String lastName;
    }

    public class JSData {
        public String city;
        public String address;
        public Array messages;

        @SerializedName("user")
        public User user;
    }
0
source

I don't know how to archive @SerializedName("user.f_name")as a path,
but the smoothed inner field is archived thanks JsonDeserializer.

Let's pretend that

 {   
   "publishDate": {
     __type: "Date",
     iso: "2014-11-05T02:27:00.000Z"
    },
 ...
 }

and we want to convert the internal "iso" field to the top "publishDate" as Date.

, JsData .

public class JsData {
  // publishDate is JSONObject. but get it as Date!
  public Date publishDate;
  ...
}

JsonDeserializer<Date> gson . gson Date, .

public static class PublishDateDeserializer implements JsonDeserializer<Date> {
    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
      // this deserializer is only for "publishDate"
      // real json is jsonobject. get inner "iso"
      String iso = json.getAsJsonObject().get("iso").getAsString();
      DateFormat parser = new SimpleDateFormat(DATE_JSON_PATTERN);
      try {
        return parser.parse(iso);
      } catch (ParseException e) {
        throw new JsonParseException(e);
      }
    }
  }

builder

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new PublishDateDeserializer()).create();
gson.fromJson(json, JsData.class);

, .

-1

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


All Articles