0

I am trying to get data from a JSON URL. Of course by AsyncTask. But the problem is the JSON file does not have Object. It is an array. JSON URL and api website

Can someone tell me how to create a JSONArray and JSONObject for this JSON file?!

Here is what I have done which makes the app stop working

//URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";

//JSON Node Names 
private static final String TAG_OBJ = "user";
private static final String NAME = "name";
private static final String CAPITALCITY = "capitalCity";
    .
    .
    .
    class GetJSONTask extends AsyncTask<String, Void, JSONObject> {


    protected JSONObject doInBackground(String... urls) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = JSONParser.getJson(url);

        return json;
    }
    protected void onPostExecute(JSONObject json) {
        //Getting JSON Array
        try {
            user = json.getJSONArray(TAG_OBJ);
            JSONObject c = user.getJSONObject(0);

            //Stroing JSON item in a Variable
            String name = c.getString(NAME);
            String capitalCity = c.getString(CAPITALCITY);

            //Importing TextView
            final TextView view1 = (TextView)findViewById(R.id.name);
            final TextView view2 = (TextView)findViewById(R.id.capitalCity);

            //Set JSON Data in TextView
            view1.setText(name);
            view2.setText(capitalCity);

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

4 Answers 4

1

Use JSON Array . Here is my code :-

String url = "http://api.androidhive.info/contacts/";
    JSONParser jParser = new JSONParser();

    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    try {
        // Getting JSON Array
        JSONArray begin = json.getJSONArray("contacts");
        JSONObject c = begin.getJSONObject(0);

        // Storing  JSON item in a Variable
        String id = c.getString("id");
        String name = c.getString("name");
        String size = c.getString("email");

Put this in your Async

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your post. It did not work. But a questions. Why should I use contacts? I have not contacts in my array.
Dude that is my example,.,. I just used another JSON to explain it to you man. DOnt copy and paste blindly. Understand the comcept
That's what I was wondering. If you compare your example with mine, everything is exactly the same. Am I right?
I am posting another answer. Please wait
@user2977338 - i have posted another answer. It is working now with your url and i am getting values for name and capitalcity
0
if(i<jArray.length()) {
         JSONObject json_obj = jArray.getJSONObject(i);   //get array object
         name = json_obj.getString("your tag name");        fetch item here
    }

1 Comment

Thanks for ur post. Can you make put it in a complete way? I mean, where should I add it to? Should I remove any part and replace it? and what is jArray?
0

Please note that i have used Strict Policy. You continue using Async Task and put my code in there. Here is my Code related to your requirement .

JsonParser.Java

    package com.example.test;

import android.os.StrictMode;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArray = null;
// constructor
public JSONParser() {

}

public JSONArray getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jArray = new JSONArray(json);
     //   jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jArray;

}
}

MainActivity.java

        package com.example.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Making HTTP request
        String url = "http://api.worldbank.org/countries/ir?format=json";
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONArray json = jParser.getJSONFromUrl(url);
        try {
            JSONArray json2 = json.getJSONArray(1); // Your second Array in your json

            for(int i=0;i<json2.length();i++){

                JSONObject c = json2.getJSONObject(i);
                // Storing  JSON item in a Variable
                String name = c.optString("name","");
                String capitalCity = c.optString("capitalCity","");

            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

2 Comments

Thanks, but I could not try it as there is an error in JSONArray json2 = json.getJSONArray(1); there should be a string instead of 1 in this line. Any idea?
You have an array at 1st position in your json. This line gets this. This code works fine. I have run it like many times now. There shouldn't be any String there as it takes in int value. Check our json. You have a JSON Array in your JSON at 1st position. This line access that part of your json. Debug your code.,.,
0

Change your MainActivity.java like below,

public class MainActivity extends Activity {

// URL to get JSON Array
private static String url = "http://api.worldbank.org/countries/ir?format=json";

// JSON Node Names
private static final String TAG_NAME = "name";
private static final String TAG_CAP_City = "capitalCity";
JSONArray responseArray = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    new GetJSONTask().execute();



}
class GetJSONTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        String json = jParser.getJSONFromUrl(url);
        return json;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

        try {
            // Getting JSON Array
            responseArray = new JSONArray(result);
            JSONArray parsedArray=responseArray.getJSONArray(1);
            JSONObject c = parsedArray.getJSONObject(0);

            // Storing JSON item in a Variable
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_CAP_City);

            // Importing TextView
            // final TextView uid = (TextView)findViewById(R.id.uid);
            final TextView name1 = (TextView) findViewById(R.id.name);
            final TextView email1 = (TextView) findViewById(R.id.email);

            // Set JSON Data in TextView
            // uid.setText(id);
            name1.setText(name);
            email1.setText(email);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

}

Also change JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public String getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        /*// try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }*/

        // return JSON String
        return json;

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.