如何访问json中的节点

时间:2014-08-01 19:22:48

标签: android json android-activity

我想在包含url的节点中访问我的json结构如下

{
    "product": {
        "name": "myApp",
        "config": [
            {
                "grade": "first",
                "courses": [
                    {
                        "name": "Math",
                        "url": "example.com"
                    }
                ]
            }
        ]
    }
}

最近我可以访问很多节点,例如等级:第一,第二,第三等,我生成一个带适配器的列表视图,然后我首先触摸一个项目,然后它将我发送到另一个包含课程的活动,我创建了相同的结构来访问课程,但当我想访问每个年级的网址时,它将我发送到最后一个网址,我如何才能访问特定的网址?对不起我的英文

2 个答案:

答案 0 :(得分:1)

使用此代码发出HTTP请求(对于您的网址中的url传递)

HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 500);

Client = new DefaultHttpClient(params);
httpget = new HttpGet(url);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
mContent = Client.execute(httpget, responseHandler);

然后使用它来获取您的数据:

   JSONObject jsonObject = new JSONObject(mContent);
   String url =json.getJSONObject("product").getJSONObject("config").getJSONObject("courses").getString("url");

OUTPUT :: String url包含您要搜索的数据!


注意 ::

  • 对于url您必须传递您尝试的网址 获得JSON响应
  • 同样将上述代码放在Asynchronous task内 崩溃,因为你正在发出网络请求

希望这会有所帮助!如果您有任何错误,请退回。

答案 1 :(得分:0)

你的json就像这个object-object-array-array-object-string。 所以你必须像MainActivity一样解析它 在解析之前,你必须从jsonparser.java中的url获取它。

这是JsonParser.java

package com.skymaster.jsonparser;

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 {

final String TAG = "JsonParser.java";

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

public JSONObject getJSONFromUrl(String url) {

    // make HTTP request
    try {

        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(TAG, "Error converting result " + e.toString());
    }

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

    // return JSON String
    return jObj;
}
}

这是你的json的MainActivity.java。

package com.skymaster.jsonparser;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // we will using AsyncTask during parsing 
    new AsyncTaskParseJson().execute();
}

// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {

    final String TAG = "AsyncTaskParseJson.java";

    // set your json string url here
    String yourJsonStringUrl = "yourjsonurlhere";


    @Override
    protected void onPreExecute() {}

    @Override
    protected String doInBackground(String... arg0) {

        try {

            // instantiate our json parser
            JsonParser jParser = new JsonParser();


            JSONObject json = jParser.getJSONFromUrl(yourJsonStringUrl);


            String url=json.getJSONObject("product").getJSONArray("config").getJSONArray("courses").getJSONObject(0).getString("url");


            }

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

        return null;
    }

    @Override
    protected void onPostExecute(String strFromDoInBg) {}
}
}