How to get part of httpResponse in java - java

I want to get just ID from httpResponse after I did HttpGet.
This is my code:
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://localhost:80/api/");
HttpResponse httpResponse = httpClient.execute(httpGet);
System.out.println(httpResponse);
BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
which returns this:
{"list":[{"timestamp":{"$date":"2014-08-01T08:37:54.058Z"},"nameGroup":false,"_id":{"$oid":"53db5045ccf2b2399e0e6128"},"created":{"$date":"2014-08-01T08:31:01.139Z"}],"name":"John"}]}
But I just want Oid not the whole thing. Any idea?
Thanks

Strint you've got is json encoded data, so you need to decode it and than you are able to access the field "oid". There are several libaries around to acomplish this job:
gson
JsonSimple
Jackson etc.
My favorite for small projects is gson

Using Jackson or Gson, you can parse the response JSON and get exactly the part you need.
If you don't need the whole result, then there is no point in creating a reference object, just manually traverse the json document, e.g.
mapper.readTree(responseText).get("foo").get("bar")

I think instead of using a library just to get value of one parameter is not appropriate if you have other options available. I would suggest you to parse the json on yor own using the APIs provided. You can try following:
try {
JSONObject obj = new JSONObject(your_json_string);
String value= null;
if (obj != null && obj.has(YOUR_KEY_FOR_PARAM)) {
value = obj.getString(YOUR_KEY_FOR_PARAM));
}
}

Related

How to put JSON information in an array to use it for displaying in ListView

I have an Activity which has three fragments and I am trying to retrieve a JSON file from my server which I will be updating on a daily basis.
My JSON file is located here: http://pagesbyz.com/test.json
Because there are fragments, I used the following code in my MainActivity class:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://pagesbyz.com/test.json");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Toast.makeText(getApplicationContext(), result, 2000).show();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
What I really need to do is retrieve the TYPE field in my JSON file and separate it into three tabs and put it inside a ListView like this:
I would like to know once I have read the JSON file by using the code on top how do I proceed... Thanks for the help :)
Should I query on each fragment and then look for the TYPE field? Would that be easier?
Curious as to why the Toast did not execute... Here is the pastebin for my main activity: http://pastebin.com/gKTCeH79
What you want to do is use Androids JSONObject and JSONArray to access your json data.
For example since your root is a json array you want to instantiate a JSONArray object from your json data you have.
JSONArray jsonArray = new JSONArray(jsonString);
Now from this array you can grab individual JSONObject for each object in your array.
JSONObject objectOne = new JSONObject(0); // Grabs your first item
From the JSONObject you can now access your three values.
String type = objectOne.get("type") // Will give you the value for type
JSONArray: http://developer.android.com/reference/org/json/JSONArray.html
JSONObject: http://developer.android.com/reference/org/json/JSONObject.html
Another way is to use a framework that lets you deserialize json into Java POJO's (Plain Old Java Objects). Gson is the easiest to use.
The basic idea is you make an object that relates directly to your json objects, after you have this you can easily store your data in java objects and use it however you like.
GSON example:
Gson gson = new Gson();
MyCustomClass obj2 = gson.fromJson(json, MyCustomClass.class);
Where MyCustomClass would contain the variables id, type, and data.
GSON reference: https://sites.google.com/site/gson/gson-user-guide
Good Luck!

Json from C# to JAVA

I have a web application in C#, and I use JsonSerializer to create a json.
Now I'm wotrking on an android application and I'm trying to read the json.
On my Android application, my code is
try {
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "android");
HttpGet request = new HttpGet();
request.setHeader("Content-Type", "application/json; charset=utf-8");
request.setURI(new URI(uri));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page); // here it explodes
}
It get explodes when trying to create a json object, because the value of "page" is
"{\\"Key\\":\\"1\\",\\"RowVersion\\":[0,0,0,0,0,0,226,148].....
When I try to get the json on the browser manually (with direct GET url), I get
"{\"Key\":\"1\",\"RowVersion\":[0,0,0,0,0,0,226,148]......
When I copy this string manually it works fine.
How can I fix it?
You are returned a JSON object as a String whereas you expected a JSON object...
With Jackson, this is easily solved:
final ObjectMapper mapper = new ObjectMapper();
// JSON object as a string...
final JsonNode malformed = mapper.readTree(response.getEntity().getContent());
// To JSON object
final JsonNode OK = mapper.readTree(malformed.textValue());
Either this, or fix the server side so as to return the JSON object!
I think that your code it too complicated, try do it like this:
String page = EntityUtils.toString(response.getEntity());

how to parse HTTPResponse object obtained using google low level api for url fetch- google app engine/java

I am using the low level API to get an HTTPResponse object as the response to my get request to a URL(an API function).
What is the quick and easy way to parse the content of that object? The response will be a JSON response, and I want to use Google GSON to convert that JSON data into Java object...
How do I accomplish this?
If your response is a string, you can do:
if (response.getCode() == 200){
String result = new String(response.getContent(), "UTF-8");
if (result != null){
Gson gson = new Gson();
YourObject obj = gson.fromJson(result,YourObject.class);
}
}

How to read the response from the HTTPClient

I am doing work around HTTPClient to send the POST request and get the response. I am getting the response code is OK.
I want to read few contents from that response HttpEntity entity =response.getEntity();
I am printing that response on console System.out.println(EntityUtils.toString(entity));.
it's printing {"created_at":"2011-12-01T07:56:50+00:00","type":"sample","id":29,"status":"received"}
I want to read the id from the above string,.
Any one can help how to retrieve the id from the entity.
Thanks in advance..
The data is JSON data.
You can go to json.org and download JSONObject.
You can do this,
JSONObject json = new JSONObject(EntityUtils.toString(entity));
int id = json.getInt("id");
It seems that you response is JSON one. can you use a JSON library, Jackson for example?
this way is not very efficent but you can try it also.
BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while(((readLine = br.readLine()) != null)) {
System.err.println(readLine);
}
if(readLine.indexOf(",") > -1 && readLine.indexOf(":") > -1)
String id = (readLine.split(",")[2]).split(":")[1];

How to use HttpClient

I'm currently trying to get some data via a 'uri' using the following code in java:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
callString = stream.toString();
return callString;
}
However this isn't working. Does anyone know what I'm doing wrong here?
You cannot print out the input stream like that... instead, do something like this:-
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://ichart.finance.yahoo.com/table.csv?s=MSFT");
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null) {
Scanner scanner = new Scanner(entity.getContent());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
}
The printout looks like this:-
1994-02-02,84.75,85.50,84.00,84.00,40924800,2.09
1994-02-01,85.00,85.75,84.50,85.12,44003200,2.12
1994-01-31,85.25,85.87,84.75,85.12,62566400,2.12
1994-01-28,84.50,85.50,84.25,84.87,41875200,2.11
1994-01-27,84.00,84.75,83.25,84.25,51129600,2.10
1994-01-26,85.00,85.00,84.00,84.25,50489600,2.10
1994-01-25,85.25,85.37,84.00,85.12,70361600,2.12
...
Its a total guess but shouldn't it be:
String uri = "ichart.finance.yahoo.com/table.csv?s=MSFT"
HttpData data = HttpRequest.get(uri);
System.out.println(data.content);
you are trying to download a file and getEntity is used get an object for a type you have specified. IMHO this wont work.
You need to code which will actually read the response stream and read contents out of it...
What are you trying to do ?
To read the resulting entity to a String use EntityUtils.toString(HttpEntity) or EntityUtils.toString(HttpEntity, String) if you know the character set.
If you are getting NetworkOnMainThreadException then that means you are calling client.execute(get); on the main thread which is an exception thrown on Honeycomb and higher. See http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html for details. The solution is to run this in a new thread.

Categories

Resources