如何在android中获取JSON DATA

时间:2014-02-18 17:07:11

标签: android json

我有JSON数据就像这样:我对获取这些json数据感到困惑。

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);
}

如果我JSONObject postListObj = jb.getJSONObject("1");然后获取列表中的所有数据,但这不是我的方式。 我想在列表中获取用户ID的JSON数据2所有标题。

JSON数据

 {
    "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"
        }

    }
}

那么,如何获取这些json数据,我想存储在列表ID和标题中。我的主要目的是在列表中显示这些标题,如果我点击 CX 获取点击的ID。在toast上显示建议删除此单击。(发布到web点击列表项。)

3 个答案:

答案 0 :(得分:2)

幸运的是,Android提供了干净且平均的实用程序来解析JSON。 如果要解析给定的JSON-String,它基本上都会降至JSONObjectJSONArray

答案 1 :(得分:0)

你在循环中拥有以下

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

你总是得到同样的标题6次。

尝试

    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();
    }

使用listMap,您可以在列表视图中显示标题和ID

日志

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

答案 2 :(得分:0)

  

太容易了。这是JSON格式:

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

&#34; userDB的&#34;是一个JSONArray标签和&#34; userId&#34; /&#34; userName&#34; /&#34; userBatch&#34; /&#34; userDep&#34;是一个字符串Tag / JSON节点名称。您可以根据需要添加字符串。在.html或.txt文件中的Web域中设置此格式数据。

  

现在在jsonTest.jsonparsing.library或你的java包中添加这个类 jsonparsing.java   本课程可帮助您阅读jeson数据。

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;

    }
}
  

现在位于jsonTest.json中的 MainActivity.java 类中,或者我们的包

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();
    }
  }   
}