H.fate H.fate - 2 months ago 5
JSON Question

On Retrofit2, If json from server is like this, How can i set json class?

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?

Answer

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()));