简体   繁体   中英

How do I access a node in json

i want to access in a node that contains an url my json structure is the following

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

Recently i could access to a lot of nodes for example grade:first,second,third etc, and i generate a listview with an adapter, then i touch an item for example first and it send me to another activity that contains courses, i create the same structure to access in courses, but when i want to access to the url for each grade it sent me to the last url how can i access to the specific url? sorry for my english

Use this code to make HTTP request (for the url pass in your 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);

Then use this to get your data:

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

OUTPUT :: String url has the data you are searching for !


Note ::

  • for the url you have to pass your url from which you are trying to get the JSON response
  • Also place the above code inside an Asynchronous task otherwise it crashes because since you are making a network request

Hope this helps! Revert back if you have any errors.

Your json is like this object-object-array-array-object-string. So you must parse it like MainActivity And before parse you must get it from url in jsonparser.java.

This is 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;
}
}

And this is MainActivity.java for your json.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM