I am trying to collect a single piece of data from an API, that being the population of a certain country. Everything works properly except for cutting the population value out of the JSON.
{"Info":[{"area":301336,"nativeName":"Italia","capital":"Rome","demonym":"Italian","flag":"https://restcountries.eu/data/ita.svg","alpha2Code":"IT","languages":[{"nativeName":"Italiano","iso639_2":"ita","name":"Italian","iso639_1":"it"}],"borders":["AUT","FRA","SMR","SVN","CHE","VAT"],"subregion":"Southern Europe","callingCodes":["39"],"regionalBlocs":[{"otherNames":[],"acronym":"EU","name":"European Union","otherAcronyms":[]}],"gini":36,"population":60665551,"numericCode":"380","alpha3Code":"ITA","topLevelDomain":[".it"],"timezones":["UTC+01:00"],"cioc":"ITA","translations":{"br":"Itália","de":"Italien","pt":"Itália","ja":"イタリア","hr":"Italija","it":"Italia","fa":"ایتالیا","fr":"Italie","es":"Italia","nl":"Italië"},"name":"Italy","altSpellings":["IT","Italian Republic","Repubblica italiana"],"region":"Europe","latlng":[42.83333333,12.83333333],"currencies":[{"symbol":"\u20ac","code":"EUR","name":"Euro"}]}]}
Within the JSON, It is called "Population".
This is my user input code
public static String UserInputsDetails() {
System.out.println("Please input the country name");
Scanner in = new Scanner(System.in);
String Input = in.nextLine();
return Input;
}
This is my JSON Getter Code
public static JSONArray MakeConnection(String countryname) {
JSONArray JSON = null;
try {
String url = "https://restcountries.eu/rest/v2/name/" + countryname;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
JSON = new JSONArray(response.toString());
} catch (Exception e) {
System.out.println(e);
}
return JSON;
}
This is my Result code, to get just the population
public static void PrintResult(JSONArray JSON){
String population = null;
try {
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
} catch (Exception e) {
System.out.println(e);
}
}
And finally, this is my main
public static void main(String []args) {
String Input = UserInput.UserInputsDetails();
JSONArray JSON = Connection.MakeConnection(Input);
Result.PrintResult(JSON);
}
I get the error
org.json.JSONException: JSONObject["population"] not found.
What am I doing wrong?
Delete this part:
JSONObject jobj = new JSONObject();
jobj.put("Info", JSON);
population = jobj.getString("population");
System.out.println(jobj);
System.out.println(population);
JSON is already an array, why are you converting it into a JSONObject?
Change to something like this:
Long population = JSON.getJSONObject(0).getLong("population");
Related
For example right now all my rest methods are working with JSONObjects, so at the client I send String JSONObject for the petitions, but what if I had one of those methods expecting an JSONArray String, in my case I have a method that generates JSONObject String with a HashMap of parameters like this:
public JsonObject generarJSON(HashMap map) throws MalformedURLException {
JsonObject json = new JsonObject();
for (Object key : map.keySet()) {
if (map.get(key) instanceof List) {
JsonParser parser = new JsonParser();
json.add(key.toString(), parser.parse((map.get(key).toString())));
} else {
json.addProperty(key.toString(), map.get(key).toString());
}
}
return json;
}
And here is the consume of the rest services:
notice that I use the above method to write to the service, it works because all my services are expecting JSONObject but what if there was one of them that expected JSONArray, how can I validate if that url needs a JSONArray format or JSONObject format? I hope you guys understand what Im trying to do.
try {
// Parametro, Properties, Ruta quemada
URL url = new URL("http://10.11.6.68:8280/" + configApp.getString("rutaService") + contexto);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/json;");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestMethod("POST");
JsonObject requestJson = new JsonObject();
requestJson = generarJSON(parametros);
OutputStream os = conn.getOutputStream();
os.write(requestJson.toString().getBytes("UTF-8"));
os.close();
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : " + conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
while ((cadenaLectura = br.readLine()) != null) {
cadenaJSON = cadenaJSON.concat(cadenaLectura);
}
conn.disconnect();
if (esJSONArray(cadenaJSON)) {
System.out.println("PARAMETROS Y JSON ARRAY");
JSONArray jsonArray = new JSONArray(cadenaJSON);
return jsonArray.toString();
} else if (esJSONObject(cadenaJSON)) {
System.out.println("PARAMETROS Y JSON OBJECT");
JSONObject json = new JSONObject(cadenaJSON);
return json.toString();
}
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
for example this is one of my methods that receive that json:
#POST
#Path("/buscarUrlCerberusPorIp")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public String buscarUrlCerberus(String data) {
logger.info("Se ejecuta el servicio buscar la URL de Cerberus por Ip");
JsonObject gson = new JsonObject();
try {
JSONObject json = new JSONObject(data);
String ipCliente = json.getString("ipCliente");
String urlCerberus = businessDelegateServiciosLocal.buscarUrlCerberus(ipCliente);
gson.addProperty("ruta", urlCerberus);
} catch (Exception e) {
logger.info("ERROR: " + e);
return null;
}
return gson.toString();
}
But what if I had one like this one:
#POST
#Path("/prueba")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public PruebaJSON prueba(String data) {
try {
JSONArray json = new JSONArray(data);
Gson convertir = new GsonBuilder().create();
PruebaJSON pruebaJson = convertir.fromJson(json.get(0).toString(), PruebaJSON.class);
return pruebaJson;
} catch (Exception e) {
System.out.println("error " + e);
return null;
}
}
notice that this one is expecting JSONArray String
I want to convert a HTTP GET request to a HTTP PATCH request. I am accessing TFS APIs and I want to lock my build automatically by using a patch request.
Currently I am getting all the information by GET method. Now I want to update keepForever from false to true using the HTTP PATCH method. By GET method I am able to do that but now I have to do that by HTTP Patch method.
Can someone help me converting the below code from GET method to POST method?
public class Test_URL_Req {
public static String getURLResponse(String url) {
try {
System.out.println("\nSending 'GET' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
// System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
public static void main(String[] args) throws JSONException{
String url = "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/definitions?api-version=4.1";
//String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response = getURLResponse(url);
// String response1 = getURLResponse(url1);
JSONObject obj_JSONObject = new JSONObject(response.toString());
JSONArray obj_JSONArray = obj_JSONObject.getJSONArray("value");
String Def_id=null;
for(int i=0; i<obj_JSONArray.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray.getJSONObject(i);
String value = obj_JSONObject2.getString("name");
String toSearch= "DEVOPS";
if(value.equals(toSearch)){
System.out.println("STATUS:-");
System.out.println(value);
String result =obj_JSONObject2.getString("name");
System.out.println("BUILD NAME");
System.out.println(result);
Def_id = obj_JSONObject2.get("id").toString();
System.out.println("DEFINATION ID");
System.out.println(Def_id);
break;
}
}
if (Def_id != null)
{
String url1 ="https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&definitions=" + Def_id +"&resultFilter=succeeded&$top=1";
String response1 = getURLResponse(url1);
JSONObject obj_JSONObject1 = new JSONObject(response1.toString());
JSONArray obj_JSONArray1 = obj_JSONObject1.getJSONArray("value");
String Build_id=null;
for(int i=0; i<obj_JSONArray1.length();i++)
{
JSONObject obj_JSONObject2 = obj_JSONArray1.getJSONObject(i);
String value = obj_JSONObject2.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
System.out.println("#######################################");
System.out.println("RESULT");
System.out.println(value);
String result =obj_JSONObject2.getString("status");
System.out.println("STATUS");
System.out.println(result);
Build_id = obj_JSONObject2.get("id").toString();
System.out.println("BUILD ID");
System.out.println(Build_id);
//boolean keepForever =obj_JSONObject2.getBoolean("keepForever");
//if(keepForever == false)
//{
// keepForever=true;
//}
// System.out.println(keepForever);
}
}
if (Build_id != null)
{
String url2= "https://tfs.tpsonline.com/IRIS%204.0%20Collection/Main/_apis/build/builds?api-version=4.1&buildNumber=" + Build_id;
String response2 = getURLResponse(url2);
JSONObject obj_JSONObject2 = new JSONObject(response2.toString());
JSONArray obj_JSONArray2 = obj_JSONObject2.getJSONArray("value");
for(int i=0; i<obj_JSONArray2.length();i++)
{
JSONObject obj_JSONObject3 = obj_JSONArray2.getJSONObject(i);
String value = obj_JSONObject3.getString("result");
//String value = obj_JSONObject2.get("id").toString();
//System.out.println(value);
String toSearch1= "succeeded";
if(value.equals(toSearch1)){
boolean keepForever =obj_JSONObject3.put("keepForever", false) != null;
if(keepForever == false)
{
keepForever = true;
}
System.out.println("#######################################");
System.out.println(keepForever);
}
}
}
}
}
}
You can just use the below to build PATCH request. However, you should also make sure that your server supports PATCH as its generally unsupported.
public static String getPatchResponse( String url){
try {
System.out.println("\nSending 'PATCH' request to URL : " + url);
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("PATCH");
con.setRequestProperty("Accept", "application/json");
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
//System.out.println(response);
}
in.close();
return response.toString();
} catch (Exception e) {
System.out.println(e);
}
return null;
}
With HTTPURLCONNECTION I am able to get the JSON response and using Writer I am able to save it to output.json file also. But I am not able to read the content of output.json or directly from the url "http://somesite.com/json/server.json" using GSON. I am facing few issues when using gson.
public class ConnectToUrlUsingBasicAuthentication {
public static void main(String[] args) {
try {
String webPage = "http://somesite.com/json/server.json";
//HTTPURLCONNECTION
URL url = new URL(webPage);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
StringBuilder sb = new StringBuilder();
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is,Charset.defaultCharset());
BufferedReader bufferedReader = new BufferedReader(isr);
String line;
while((line = bufferedReader.readLine()) != null) {
System.out.println("*** BEGIN ***");
try(Writer writer = new OutputStreamWriter(new FileOutputStream("Output.json") , "UTF-8")){
Gson gson = new GsonBuilder().create();
gson.toJson(line, writer);
System.out.println("Written successfully");
}
System.out.println(line);
System.out.println("*** END ***");
try(Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The other class I am passing during gson.fromjson call is Jsondata.
public class JsonData {
private String body;
private List<String> items = new ArrayList<String>();
private List<String> messages = new ArrayList<String>();
// Getters and setters are not required for this example.
// GSON sets the fields directly using reflection.
#Override
public String toString() {
return messages + " - " + items + " - " + messages ;
}
}
Outputs:
Json format (Is the JSON format looks fine or any syntax error is there in it)
line = {
"body":
{"items":[
{"name":"server","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server1","state":"RUNNING","health":"HEALTH_OK"},
{"name":"server2","state":"RUNNING","health":"HEALTH_OK"}
]},
"messages":[]}
Value printed for variable p is null.
Could some one please help me in printing the Json response in variable p using Gson.
Wait until you've read the entire response body before you try and convert it with GSON.
try (Writer writer = new OutputStreamWriter(
new FileOutputStream("Output.json") , "UTF-8")) {
Gson gson = new GsonBuilder().create();
while((line = bufferedReader.readLine()) != null) {
gson.toJson(line, writer);
}
}
// Now read it.
try (Reader reader = new InputStreamReader(is, "UTF-8")){
Gson gson = new GsonBuilder().create();
JsonData p = gson.fromJson(reader, JsonData.class);
System.out.println(p);
}
I want to get a JSON object from a Http get response:
Here is my current code for the Http get:
protected String doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(params[0]);
HttpResponse response;
String result = null;
try {
response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
// now you have the string representation of the HTML request
System.out.println("RESPONSE: " + result);
instream.close();
if (response.getStatusLine().getStatusCode() == 200) {
netState.setLogginDone(true);
}
}
// Headers
org.apache.http.Header[] headers = response.getAllHeaders();
for (int i = 0; i < headers.length; i++) {
System.out.println(headers[i]);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return result;
}
Here is the convertSteamToString function:
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Right now I am just getting a string object. How can I get a JSON object back.
The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.
If you are supposed to get a JSON Object you can just put:
JSONObject myObject = new JSONObject(result);
Do this to get the JSON
String json = EntityUtils.toString(response.getEntity());
More details here : get json from HttpResponse
This is not the exact answer for your question, but this may help you
public class JsonParser {
private static DefaultHttpClient httpClient = ConnectionManager.getClient();
public static List<Club> getNearestClubs(double lat, double lon) {
// YOUR URL GOES HERE
String getUrl = Constants.BASE_URL + String.format("getClosestClubs?lat=%f&lon=%f", lat, lon);
List<Club> ret = new ArrayList<Club>();
HttpResponse response = null;
HttpGet getMethod = new HttpGet(getUrl);
try {
response = httpClient.execute(getMethod);
// CONVERT RESPONSE TO STRING
String result = EntityUtils.toString(response.getEntity());
// CONVERT RESPONSE STRING TO JSON ARRAY
JSONArray ja = new JSONArray(result);
// ITERATE THROUGH AND RETRIEVE CLUB FIELDS
int n = ja.length();
for (int i = 0; i < n; i++) {
// GET INDIVIDUAL JSON OBJECT FROM JSON ARRAY
JSONObject jo = ja.getJSONObject(i);
// RETRIEVE EACH JSON OBJECT'S FIELDS
long id = jo.getLong("id");
String name = jo.getString("name");
String address = jo.getString("address");
String country = jo.getString("country");
String zip = jo.getString("zip");
double clat = jo.getDouble("lat");
double clon = jo.getDouble("lon");
String url = jo.getString("url");
String number = jo.getString("number");
// CONVERT DATA FIELDS TO CLUB OBJECT
Club c = new Club(id, name, address, country, zip, clat, clon, url, number);
ret.add(c);
}
} catch (Exception e) {
e.printStackTrace();
}
// RETURN LIST OF CLUBS
return ret;
}
}
Again, it’s relatively straight forward, but the methods I’ll make special note of are:
JSONArray ja = new JSONArray(result);
JSONObject jo = ja.getJSONObject(i);
long id = jo.getLong("id");
String name = jo.getString("name");
double clat = jo.getDouble("lat");
Without a look at your exact JSON output, it's hard to give you some working code. This tutorial is very useful, but you could use something along the lines of:
JSONObject jsonObj = new JSONObject("yourJsonString");
Then you can retrieve from this json object using:
String value = jsonObj.getString("yourKey");
For the sake of a complete solution to this problem (yes, I know that this post died long ago...) :
If you want a JSONObject, then first get a String from the result:
String jsonString = EntityUtils.toString(response.getEntity());
Then you can get your JSONObject:
JSONObject jsonObject = new JSONObject(jsonString);
You need to use JSONObject like below:
String mJsonString = downloadFileFromInternet(urls[0]);
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
...
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}
catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
Hope this helps you..
There is a JSONObject constructor to turn a String into a JSONObject:
http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
If your api is response is a java object, then the string that you got from Outputstream should be in json string format such as
{\"name\":\"xyz\", \"age\":21}
. This can be converted to JSON object in many ways, out of which one way is to use google GSON library.
GsonBuilder builder = new GsonBuilder().setPrettyPrinting(); Gson gson = builder.create(); <javaobject> = gson.fromJson(<outputString>, <Classofobject>.class);
One can do it without Gson also, using Jackson, which implements Json Tree Model.
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(responseString);
1)String jsonString = EntityUtils.toString(response.getEntity());
2)JSONObject jsonObject = new JSONObject(jsonString);
I am doing basic http auth with the HttpURLConnection object in Java.
URL urlUse = new URL(url);
HttpURLConnection conn = null;
conn = (HttpURLConnection) urlUse.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(timeout);
conn.setReadTimeout(timeout);
conn.connect();
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
}
I am expecting a JSON object, or string data in the format of a valid JSON object, or HTML with simple plain text that is valid JSON. How do I access that from the HttpURLConnection after it returns a response?
You can get raw data using below method. BTW, this pattern is for Java 6. If you are using Java 7 or newer, please consider try-with-resources pattern.
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
And then you can use returned string with Google Gson to map JSON to object of specified class, like this:
String data = getJSON("http://localhost/authmanager.php");
AuthMsg msg = new Gson().fromJson(data, AuthMsg.class);
System.out.println(msg);
There is a sample of AuthMsg class:
public class AuthMsg {
private int code;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
JSON returned by http://localhost/authmanager.php must look like this:
{"code":1,"message":"Logged in"}
Regards
Define the following function (not mine, not sure where I found it long ago):
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Then:
String jsonReply;
if(conn.getResponseCode()==201 || conn.getResponseCode()==200)
{
success = true;
InputStream response = conn.getInputStream();
jsonReply = convertStreamToString(response);
// Do JSON handling here....
}
In addition, if you wish to parse your object in case of http error (400-5** codes),
You can use the following code: (just replace 'getInputStream' with 'getErrorStream':
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getErrorStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
The JSON string will just be the body of the response you get back from the URL you have called. So add this code
...
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.
Here's an example using JSON-LIB
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;