Parsin JSON信息 - Android工作室

时间:2017-11-04 11:01:26

标签: java android json parsing

我目前正在尝试解析一个简单的JSON信息,但无法找出JSON对象和数组部分......我正在尝试从此JSON中提取(下面)app_time和邮政编码+地址。任何人都可以给我一个关于我的“extractFeatureFromJson()”的解决方案,抱歉格式化是我在这里的第一篇文章。

{
"data": [
{
"id": 24256,
"app_time": 1904280242,
"addresses": [
{
"id": 1,
"postcode": "9000",
"address": "Street:Street, City: City, Country: Country"
}
],
"comments": [
{
"id": 1,
"comment": "Comment",
"created_at": 234234234
}
]
}
]
}


public static final String LOG_TAG = MainActivity.class.getSimpleName();

private static final String _URL = "https://.......com/";

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

private void updateUi(Event job) {

    TextView titleTextView = (TextView) findViewById(R.id.time);
    titleTextView.setText(getDateString(job.time));

    TextView dateTextView = (TextView) findViewById(R.id.address);
    dateTextView.setText(job.address);
}

private String getDateString(long timeInMilliseconds) {
    SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
    return formatter.format(timeInMilliseconds);
}





private class ScheduleAsyncTask extends AsyncTask<URL, Void, Event> {

    @Override
    protected Event doInBackground(URL... urls) {
        // Create URL object
        URL url = createUrl(_URL);

        // Perform HTTP request to the URL and receive a JSON response back
        String jsonResponse = "";
        try {
            jsonResponse = makeHttpRequest(url);
        } catch (IOException e) {
            // TODO Handle the IOException
        }
        Event jobs = extractFeatureFromJson(jsonResponse);


        return jobs;

    }




    @Override
    protected void onPostExecute(Event job) {
        if (job == null) {
            return;
        }

        updateUi(job);
    }

    /**
     * Returns new URL object from the given string URL.
     */
    private URL createUrl(String stringUrl) {
        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException exception) {
            Log.e(LOG_TAG, "Error with creating URL", exception);
            return null;
        }
        return url;
    }



    private String makeHttpRequest(URL url) throws IOException {
        String jsonResponse = "";
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("X-Application", ".....");
            urlConnection.connect();
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } catch (IOException e) {
            // TODO: Handle the exception
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                // function must handle java.io.IOException here
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private String readFromStream(InputStream inputStream) throws IOException {
        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }



    private Event extractFeatureFromJson(String scheduleJSON) {
        try {
            JSONObject baseJsonResponse = new JSONObject(scheduleJSON);
            JSONArray featureArray = baseJsonResponse.getJSONArray("comments");

            // If there are results in the features array

                // Extract out the first feature 
                JSONObject firstFeature = featureArray.getJSONObject(0);
                JSONObject properties = firstFeature.getJSONObject("comment");

                // Extract out the time address values
                String address = properties.getString("address");
                long time = properties.getLong("app_time");


                // Create a new {@link Event} object
                return new Event(address, time);

        } catch (JSONException e) {
            Log.e(LOG_TAG, "Problem parsing the JSON results", e);
        }
        return null;
    }

}
}

2 个答案:

答案 0 :(得分:0)

根据你的json结构,数据是json数组,地址和注释也是如此,所以你必须按照json数组和json对象的方式工作。

理解json结构的一种方法(对象和数组是格式化它并查看它。使用在线json格式化程序如https://jsonformatter.org/或在notepad ++中安装插件来格式化json。

注意: 我没有给你完整的解决方案,因为它是为了你自己的利益所以这是你应该做的,并添加调试器点和system.out.println (在android中的Log.d)用于理解你遍历和学习的json对象和数组。

JSONObject obj = new JSONObject(str);
JSONObject appTime = obj.getJSONArray("data").getJSONObject(0).getJSONObject(“app_time”);
JSONObject postal_code = obj.getJSONArray("data").getJSONObject(0).getJSONArray(“addresses”).getJSONObject(0).getJSONObject(“postcode”);

您必须在每个步骤添加适当的空值检查以避免NPE。

您还可以使用JSONObject的方法来检索特定的数据类型(getString,getLong等)

https://developer.android.com/reference/org/json/JSONObject.html

答案 1 :(得分:0)

    if (scheduleJSON!= null) {
                    try {
                        JSONObject jsonObj = new JSONObject(scheduleJSON);

                        // Getting JSON Array node
                        JSONArray data= jsonObj.getJSONArray("data");

     // looping through All data
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject id = data.getJSONObject(id);
                            JSONObject app_time=data.getJSONObject(app_time);
                            String id = c.getString("id");

                            // Getting JSON Array node
JSONArray addresses=new JSONArray(data.getJSONObject(i).getString("addresses"));
JSONArray comments= new JSONArray(data.getJSONObject(i).getString("comments"));

}

    }catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());

    }