简体   繁体   中英

In Android How To Parse The JSON Array

I have crated web api as http://hunttreasure.azurewebsites.net/Default.aspx It returns jason array as

[{
    "latitude": 20.938849,
    "longitude": 77.781681,
    "placeName": "SBI_CAMP",
    "hint": "SBI CAMP Treasure Hint"
}, {
    "latitude": 20.938835,
    "longitude": 77.782726,
    "placeName": "GARAGE CAMP",
    "hint": "CAMP GARAGE Treasure Hint"
}]

How Can I Parse this JSON Array Getting From URL and Save the values in Variables.

Just a sample

public class Language extends Json {

    private String mUuid;
    private String mName;

    public Language() { }

    public String getName() {
        return mName;
    }

    public void setName(final String name) {
        mName = name;
    }

    public String getUuid() {
        return mUuid;
    }

    public void setUuid(final String uuid) {
        mUuid = uuid;
    }

    @Override
    public void init(final String... args) {
        final String jsonStr = args[0]; //Here we get a json object like a string

        try {
            JSONObject json = new JSONObject(jsonStr); //Parse it
            mUuid = json.getString("Id");
            mName = json.getString("Name");

            mIsOk = true;
        } catch (JSONException e) {
            e.printStackTrace();
            mIsOk = false;
        }
    }
}

For JSON array you should use JSONArray instead of JSONObject .
ADDED

URL url = new URL(mPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(mTimeout);
int code = connection.getResponseCode();
boolean isOk = HttpRequest.HTTP_OK == code;

if (isOk) {
    String response = ConnectionUtils.readToString(connection.getInputStream());
}
package com.example.its.myapplication;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private String finalresult;

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

    private class GetJsonData extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // before making http calls

        }

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


            String getUrl = "http://hunttreasure.azurewebsites.net/Default.aspx ";
            try {
                URL url;
                HttpURLConnection urlConnection = null;
                url = new URL(getUrl);

                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");

                StringBuffer response = new StringBuffer();
                int responseCode = urlConnection.getResponseCode();

                if (responseCode == HttpURLConnection.HTTP_OK) { //success
                    BufferedReader inurl = new BufferedReader(new InputStreamReader(
                            urlConnection.getInputStream()));
                    String inputLine;
                    while ((inputLine = inurl.readLine()) != null) {
                        response.append(inputLine);
                    }
                    inurl.close();

                } else {

                    Log.i("test", "POST request not worked.");
                }

                finalresult = response.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            try {
                parseJson(finalresult);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        public void parseJson(String json) throws JSONException {

            JSONArray jArr = new JSONArray(json);

            for (int count = 0; count < jArr.length(); count++) {
                JSONObject obj = jArr.getJSONObject(count);
                double latitude= obj.getDouble("latitude");
                double longitude= obj.getDouble("longitude");
                String placeName= obj.getString("placeName");
                String hint = obj.getString("hint");
            }
        }

    }}

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