How would I get a particular value from a JSON? - android

I'm trying to get a particular value from a field within a JSON file. This is my first time working with a JSON file so I'm not sure if I'm doing it correctly.
try {
URL url = new URL(API_URL + city +".json");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
This block would get the JSON from a weather website and then return the JSON as a string. This string would then be used below. Unfortunately whenever I run this app in Android Studio and go through the logs the logs constantly say that there was no value in weather.
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
responseView.setText(response);
// TODO: check this.exception
// TODO: do something with the feed
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
String weather = object.getString("weather");
Toast.makeText(MyActivity.this, "There is rain", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
What I'm trying to do is grab information from the weather section
Here is the JSON link I'm trying to parse from. This text box thought there were too many links in the JSON response for me to post it here. I'm trying to figure out what is going on and any help would be greatly appreciated.

You can print out response to see if it is exactly your JSON or not.
Assume you get the JSON String correctly.
JSONObject object = new JSONObject(response);
String weather = object.getString("weather");
However, if the JSON your obtained is exactly your response, the above code do not work because there is not weather String. The root only contain response and current_observation.
If what you what to get is weather under current_observation, you should use the code below.
JSONObject object = new JSONObject(response);
JSONObject current_obs = object.getJSONObject("current_observation");
String weather = current_obs.getString("weather"); // Clear

JSONObject object = (JSONObject) new JsonObject(responseString);
String weather = object.getString("weather");

First you need to get your response in string.
Now,start json parsing as per response.
OR
You can use Gson class as well for json parsing.
Get json value from JSONObject:
{"weather":"sunny"}
code snippet to parse the JSONObject.
JSONObject object = new JsonObject(response);
String weather= object.getString("weather");
Get json value from JSONArray:
[{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...]
code snippet to parse the JsonArray.
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
Hope it'll help you.

I have a sample Weather app done using open weather map api. It has all you asked for.
Code here:
http://opensourceandroid.in/weather_forecast.html

Related

org.json.JSONArray cannot be converted to JSONObject ANDROID

I am creating a app in Android and trying to read Json value from the service I created in C# using MVC. The service is returning the follwing Json response.
[{"empID":"1","Fname":"Khayyam","SurName":"Studenti","DOB":null,"gender":null},{"empID":"2","Fname":"Student 2","SurName":"Zaheer","DOB":null,"gender":null}]
The following section of program is fetching the value from web service and storing in string.
_input = new BufferedReader(new InputStreamReader(_urlConnection.getInputStream()));
String _data;
StringBuilder _Sb = new StringBuilder();
while((_data = _input.readLine() )!=null){
_Sb.append(_data);
_Sb.append(System.getProperty("line.separator"));
}
_RestfulString= _Sb.toString();
.....
and in the postExecution of AsyncTask
protected void onPostExecute(Void unused){
JSONObject _response;
try{
_response = new JSONObject(_RestfulString);
JSONArray _jsonNodes = _response.optJSONArray("rest");
for(int x=0; x< _RestfulString.length();x++){
JSONObject _childNode = _jsonNodes.getJSONObject(x);
Log.d("Fname",_childNode.optString("Fname"));
txtFname.setText(_childNode.optString("Fname"));
txtSname.setText(_childNode.optString("SurName"));
txtDOB.setText(_childNode.optString("DOB"));
}
}
catch (Exception exp) {
Log.d("Excetpion",exp.getMessage());
_pDialog.hide();
}
}
As soon as the program hits
_response = new JSONObject(_RestfulString);
it raise exception of
Value [{"empID":"1","Fname":"Muhammad Khayyam","SurName":"Qureshii","DOB":null,"gender":null},{"empID":"2","Fname":"Sobia","SurName":"Zaheer","DOB":null,"gender":null}]
of type org.json.JSONArray cannot be converted to JSONObject
It is clearly visible that the input is in JSONArray and you are attempting to convert it into JSONObject and your desired JSONObject is perhaps at 0th index of it. Try below code
JSONArray arr=new JSONArray(_RestfulString);
_response=arr.getJSONObject(0);

Parsing json object from google api returning null

I am making a simple application where i scan the barcode of a book and fetch its title and author from Google APIs,
Now, this is the url for json(for a particular book i am scanning)
https://www.googleapis.com/books/v1/volumes?q=isbn:9788120305960
using this code to get json in a string
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
response+=line;
}
bufferedReader.close();
inputStream.close();
urlConnection.disconnect();
Log.d("Info",response);
return response;
I store the result in a string and use this code to parse through
(json_response is a string)
JSONObject rootObject = new JSONObject(json_response);
JSONArray items = rootObject.getJSONArray("items");
JSONObject items_object = items.getJSONObject(0);
JSONObject volume_info = items_object.getJSONObject("volumeInfo");
book.setTitle(volume_info.getString("title"));
JSONArray authors = volume_info.getJSONArray("authors");
Log.d("Info","authors array length: "+authors.length());
String author="";
for (int i =0;i<authors.length();i++)
{
author+=authors.getString(i)+", ";
}
book.setAuthor(author);
The exception is:
Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
also I used logcat to see what is contained in json_response it looks something like this
null{ "kind": "books#volumes", "totalItems": 1, "items":...
The null here is probably causing the problem, so... any insights how to deal with this???
PS: I am a student , dealing first time with json and android, code is unprofessional, please pardon :)
Having
null{ "kind": "books#volumes", "totalItems": 1, "items":...
means that the response value has not been initialised.
You should therefore initialise it to empty string.

How to Parse from the JSON file? [duplicate]

This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 9 years ago.
I have following objects in JSON file. I have to parse it and store it in a file. What will be the android code for doing this?
{
"result":"ok",
"numbers":
[
{
"First":"first",
"Second":"second",
"Third":"third",
"Fourth":"fourth",
"Fifth":"fifth"
}
]
}
Any one find me getting out of this? I would really appreciate your work.
{ -> json object
"result":"ok",
"numbers":[-> json array
{
Do like this
JSONObject jobject=new JSONObject(jsonString);
JSONArray jarray=Jobject.getJSONArray("numbers");
String result=jobject.getJSONObject("result");
for(int i=0;jarray.length();i++){
String first= jarray.getJSONObject(i).getString("First");
String Second= jarray.getJSONObject(i).getString("Second");
}
{ // json object node
"result":"ok",
"numbers":[// json array numbers
{
"First":"first",
To parse
JSONObject jb = new JSONObject("your json");
String result = (JSONArray)jb.getString("result");
JSONArray jr = (JSONArray)jb.getJSONArray("numbers");
JSONObject jb1= (JSONObject) jr.getJSONObject(0);
String first = jb1.getString("First");
// similarly for second third and fourth
Once you parse you can write the result to a file.
Edit:
Note: Network operation must be done in a background thread. Use Asynctask
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("your json url ");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
}catch(Exception e)
{
e.printStackTrace();
}
Now use _response JSONObject jb = new JSONObject("_response);. Rest all is the same
Try Using the following
import org.json.JSONArray;
import org.json.JSONObject;
JSONObject json = null;
JSONArray jsonArray = null;
String data = null;
json = new JSONObject(response);
data = json.getString("numbers");
jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
String str =jsonArray.getJSONObject(i).toString();
}
always remember { means object and [ means array so you can proceed with following code in the give
JSONObject firstjobject=new JSONObject(jsonString);
JSONArray firstjarray=firstjobject.getJSONArray("numbers");
String result=firstjobject.getJSONObject("result");
for(int i=0;firstjarray.length();i++){
String first= firstjarray.getJSONObject(i).getString("First");
String Second= firstjarray.getJSONObject(i).getString("Second");
}
here numbers is an array and First,Second etc are the keys for relative data values

How to check if response from server is JSONAobject or JSONArray? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray
I have a server that returns some JSONArray by default, but when some error occurs it returns me JSONObject with error code. I'm trying to parse json and check for errors, I have piece of code that checks for error:
public static boolean checkForError(String jsonResponse) {
boolean status = false;
try {
JSONObject json = new JSONObject(jsonResponse);
if (json instanceof JSONObject) {
if(json.has("code")){
int code = json.optInt("code");
if(code==99){
status = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status ;
}
but I get JSONException when jsonResponse is ok and it's a JSONArray (JSONArray cannot be converted to JSONOBject)How to check if jsonResponse will provide me with JSONArray or JSONObject ?
Use JSONTokener. The JSONTokener.nextValue() will give you an Object that can be dynamically cast to the appropriate type depending on the instance.
Object json = new JSONTokener(jsonResponse).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
//further actions on jsonObjects
//...
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
//further actions on jsonArray
//...
}
You are trying the convert String response you get from Server into JSONObject which is causing the Exception. As you said you will get the JSONArray from Server, you try to convert into JSONArray. Please refer this link which will help you when to convert string response to JSONObject and JSONArray. If you response starts with [ (Open Square Bracket) then convert it to JsonArray as below
JSONArray ja = new JSONArray(jsonResponse);
if your response starts with { (open flower Bracket) then convert it to
JSONObject jo = new JSONObject(jsonResponse);

How do I prevent my app from crashing unexpectedly, "force close", when using JSON data, and handle the exception instead?

In my application, I have a food activity in which the user enters his/her food, and the app requests the food, by the name entered by the user, from a MYSQL database. In the case that the entered food not exist, the string returned by the database should be null.
Currently, when this happens, an exception to occurs since the null value cannot be parsed to a JSON array. My question is: "Is there a way to prevent my app from force closing? Can I handle the exception and display a toast notifying the user that the requested food was not found?" I would like to prevent the app from crashing, and, rather, fail gracefully.
Please help me.
I've shown the relevant code in my application..
private class LoadData extends AsyncTask<Void, Void, String>
{
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private String entered_food_name=choice.getText().toString().trim();
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... params)
{
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/food.php");
nameValuePairs.add(new BasicNameValuePair("Name",entered_food_name));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
//convert response to string
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result =sb.toString();
result = result.replace('\"', '\'').trim();
}
catch(Exception e){
Log.e("log_tag", " connection" + e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try{
String foodName="";
int Description=0;
jArray = new JSONArray(result); // here if the result is null an exeption will occur
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
foodName=json_data.getString("Name");
.
.
.
.
.
}
catch(JSONException e){
**// what i can do here to prevent my app from crash and
// make toast " the entered food isnot available " ????**
Log.e("log_tag", "parssing error " + e.toString());
}
}
}
This will fix your code:
jArray = (result == null) ? new JSONArray() : new JSONArray(result);
Now that you have an empty JSONArray, you will be able to test for null JSONObjects later in your program. Many of the JSON methods return a JSONObject if one is found, of null if none exists.
You might also want to initialize your JSONObject with the no-argument JSON constructor, rather than simply setting it to null. It will avoid problems when passing it to other JSON methods (such as using it in a constructor to a JSONArray():
JSONObject json_data = new JSONObject();
Finally, if you're still getting JSONExceptions, it's because you're not actually passing a valid JSON string to the constructor. You can print out the value of result to the log:
Log.d("JSON Data", result);
You may see some SQL error text or if you retrieve from a web server, then an HTTP error code (404 is common if you don't have your url correct).
If your result does look like JSON, then you can verify whether it's actually valid JSON or not using the JSONLint validator. It will help you catch any errors you may have, especially if you're formatting the JSON yourself.
Are you looking to capture the Exception and log it (remotely) to aid in crash reporting and debugging? I've used this package to remotely capture Exceptions and it works pretty good:
http://code.google.com/p/android-remote-stacktrace/

Categories

Resources