No_Name_Code
No_Name_Code

Reputation: 299

How to get JSON DATA in android

I have JSON Data Like this: I have little confused by getting these json data.

JSONObject jb = (JSONObject)entries.getJSONObject("data"); 
Log.d("Geting Value---", "+----"+jb.length()); //here i got 6 length.
for (int i = 0; i < jb.length(); i++) {
JSONObject postListObj = jb.getJSONObject("1");

String Title = postListObj.getString("title");

namelist.add(Title);
}

if i JSONObject postListObj = jb.getJSONObject("1"); then getting all data in list, but it is not my way. I want to get JSON data of user id here 2 in list all title.

JSON Data

 {
    "get": [],
    "post": {
        "event": "datajson",
        "user_id": "2"
    },
    "data": {
        "3": {
            "ID": 1,
            "title": "A"
        },
        "4": {
            "ID": 2,
            "title": "B"
        },
        "5": {
            "ID": 5,
            "title": "X"
        },
        "6": {
            "ID": 1172,
            "title": "dsfsdf"
        },
        "7": {
            "ID": 34,
            "title": "CX"
        },
        "8": {
            "ID": 8,
            "title": "Z"
        }
        
    }
}

SO, How to get these json data and i want to store in list id and titles. My main intention is display these title in list and if i click CX get id of clicked. display on toast for propose of delete this clicked.(post to web clicked list item.)

Upvotes: 1

Views: 1006

Answers (3)

Md Imran Choudhury
Md Imran Choudhury

Reputation: 9997

It's too easy. This is JSON format :

{
"userDB": [
        {
         "userId": "UG02-00-00-000",
         "userName": "Jon",
         "userBatch": "2nd",
         "userDep": "C.S.E"
        }
    ]
}

"userDB" is a JSONArray Tag and "userId"/"userName"/"userBatch"/"userDep" is a string Tag/JSON Node Names .You can add string as you want. Set this format data on your web domain in .html or .txt file.

Now add this class in jsonTest.jsonparsing.library or your java package jsonparsing.java This class help you to read jeson data.

package jsonTest.jsonparsing.library;    
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.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject 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 jObj;

    }
}

Now in your MainActivity.java class in jsonTest.jsonparsing this or our package

package jonTest.jsonparsing;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

import jsonTest.jsonparsing.library.JSONParser;


public class MainActivity extends Activity {

    //URL to get JSON Array this is the main part pass add your URL which return data, If link not working then save JSON your domain and then set URL
    private static String url = "http://yourlink";

    //JSON Node Names 
    //set TAG must same name which you use in your JSON and add tag as you want.
private static final String TAG_USER = "userDB";
private static final String TAG_ID = "roll";
private static final String TAG_NAME = "name";
private static final String TAG_BATCH= "userBatch";
    private static final String TAG_DEP = "dept";

    JSONArray user = null;



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

        setContentView(R.layout.activity_main);

        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);

        try {
            // Getting JSON Array
            user = json.getJSONArray(TAG_USER);
            JSONObject c = user.getJSONObject(0);

        // Storing  JSON item in a Variable
        String id = c.getString(TAG_ID);
        String name = c.getString(TAG_NAME);
        String userBatch = c.getString(TAG_BATCH);
        String dep = c.getString(TAG_DEP);

            /*
            //Importing TextView just for show data in value
            final TextView uid = (TextView)findViewById(R.id.uid);
            final TextView name1 = (TextView)findViewById(R.id.name);
            final TextView batch1 = (TextView)findViewById(R.id.batch);
            final TextView dep1 = (TextView)findViewById(R.id.dep);
            //Set JSON Data in TextView
            uid.setText(id);
            name1.setText(name);
            batch1.setText(totalSub);
            dep1.setText(dep); */

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

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

You are having the below in a loop

 JSONObject postListObj = jb.getJSONObject("3");
 String Title = postListObj.getString("title");

You always get the same title 6 times.

Try

    ArrayList<HashMap<String,String>> listMap= new ArrayList<HashMap<String,String>>();
    try
    {
        JSONObject entries = new JSONObject(load()) ;
        JSONObject dataObject = entries.getJSONObject("data");

        Iterator<String> keysIterator = dataObject.keys();
        while (keysIterator.hasNext()) 
        {
                HashMap<String,String> map = new HashMap<String,String>();
                String keyStr = (String)keysIterator.next();
                JSONObject postListObj = dataObject.getJSONObject(keyStr);
                int  key = postListObj.getInt("ID");
                String value = postListObj.getString("title");
                map.put(key, value);
                listMap.add(map);
                Log.i("Key is.....",""+key);
                Log.i("Value is....",value);
        }  

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

Use the listMap and you can display both title and id in a listview

Log

02-18 12:42:09.757: I/Key is.....(1351): 1
02-18 12:42:09.757: I/Value is....(1351): A
02-18 12:42:09.757: I/Key is.....(1351): 8
02-18 12:42:09.767: I/Value is....(1351): Z
02-18 12:42:09.767: I/Key is.....(1351): 34
02-18 12:42:09.767: I/Value is....(1351): CX
02-18 12:42:09.767: I/Key is.....(1351): 1172
02-18 12:42:09.767: I/Value is....(1351): dsfsdf
02-18 12:42:09.767: I/Key is.....(1351): 5
02-18 12:42:09.767: I/Value is....(1351): X
02-18 12:42:09.767: I/Key is.....(1351): 2
02-18 12:42:09.767: I/Value is....(1351): B

Upvotes: 0

poitroae
poitroae

Reputation: 21367

Luckily, Android offers clean and mean utilities to parse JSON. It basically all falls down to JSONObject and JSONArray if you want to parse a given JSON-String.

Upvotes: 2

Related Questions