Reputation: 644
If i get json form as like follows, How should i set Postitem class?
{
"author": "1122",
"text": "ggg",
"image": "https://www.landscape.com/irenepretty",
"point": {
"longitude": "-4.921875",
"latitude": "13.974609375"
}
}
I wrote
public class Postitem implements Serializable {
@Expose
private String author;
@Expose
private String text;
@Expose
private String image;
}
But i don't know how to make it about "point"
Could you teach me?
Upvotes: 1
Views: 61
Reputation: 3755
One way is to make another class as Point like this:
public class Point{
@Expose
private double latitude;
@Expose
private double longitude;
}
and have your PostItem like this:
public class Postitem implements Serializable {
@Expose
private String author;
@Expose
private String text;
@Expose
private String image;
@Expose
private Point point;
}
Another way is just store them as jsonobject like this:
If you are using Gson you can use it like this:
public class Postitem implements Serializable {
@Expose
private String author;
@Expose
private String text;
@Expose
private String image;
@Expose
private JSONObject point;
}
Then you need a deserializer which is like this:
public class JsonObjectDeserializer<J> implements com.google.gson.JsonDeserializer<JSONObject> {
@Override
public JSONObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
if (json.isJsonObject()) {
String value = json.getAsJsonObject().toString();
try {
return new JSONObject(value);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (json.isJsonArray()) {
JSONObject object = new JSONObject();
try {
object.put("array", new JSONArray(json.getAsJsonArray().toString()));
return object;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
And then you need to register the deserializer with retrofit like this:
Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory
.create(
new GsonBuilder()
.registerTypeAdapter(
JSONObject.class,
new JsonObjectDeserializer()
)
.create()));
Upvotes: 1
Reputation: 3771
public class Postitem implements Serializable {
@Expose
private String author;
@Expose
private String text;
@Expose
private String image;
@Expose
private Point point;
public class Point implements Serializable {
@Expose
private double longitude;
@Expose
private double latitude;
}
}
Upvotes: 1
Reputation: 432
you can first make pojo class : like this
@JsonProperty("author")
private String author;
@JsonProperty("text")
private String text;
@JsonProperty("image")
private String image;
@JsonProperty("point")
private Point point;
Now Point is a class which will have lat and long as variables
public class Point {
@JsonProperty("longitude")
private String longitude;
@JsonProperty("latitude")
private String latitude;
}
Upvotes: 1