This function will be used to retrieve data from the URL as an 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); }
The function above is called here, and we get a json string form using the Apache Class library. And in the following statements, we are trying to make a simple pojo from the json we got.
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 json input. public class JsonJavaModel {String content; Line header; } This is a custom deserializer:
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 the Gson library and org.apache.http.util.EntityUtils;
Uzair May 13 '15 at 11:48 2015-05-13 11:48
source share