This function will be used get the data from url in form of HttpResponse object.
public HttpResponse getRespose(String url, String your_auth_code){
HttpClient client = new DefaultHttpClient();
HttpPost postForGetMethod = new HttpPost(url);
postForGetMethod.addHeader("Content-type", "Application/JSON");
postForGetMethod.addHeader("Authorization", your_auth_code);
return client.execute(postForGetMethod);
}
Above function is called here and we receive a String form of the json using the Apache library Class.And in following statements we try to make simple pojo out of the json we received.
String jsonString =
EntityUtils.toString(getResponse("http://echo.jsontest.com/title/ipsum/content/ blah","Your_auth_if_you_need_one").getEntity(), "UTF-8");
final GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(JsonJavaModel .class, new CustomJsonDeserialiser());
final Gson gson = gsonBuilder.create();
JsonElement json = new JsonParser().parse(jsonString);
JsonJavaModel pojoModel = gson.fromJson(
jsonElementForJavaObject, JsonJavaModel.class);
This is a simple java model class for incomming json. public class JsonJavaModel{ String content; String title; } This is a custom deserialiser:
public class CustomJsonDeserialiserimplements JsonDeserializer<JsonJavaModel> {
@Override
public JsonJavaModel deserialize(JsonElement json, Type type,
JsonDeserializationContext arg2) throws JsonParseException {
final JsonJavaModel jsonJavaModel= new JsonJavaModel();
JsonObject object = json.getAsJsonObject();
try {
jsonJavaModel.content = object.get("Content").getAsString()
jsonJavaModel.title = object.get("Title").getAsString()
} catch (Exception e) {
e.printStackTrace();
}
return jsonJavaModel;
}
Include Gson library and org.apache.http.util.EntityUtils;