【问题标题】:Parsin JSON information - Android studio解析 JSON 信息 - Android studio
【发布时间】:2017-11-04 11:01:25
【问题描述】:

我目前正在尝试解析一个简单的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;
    }

}
}

【问题讨论】:

    标签: java android json parsing


    【解决方案1】:

    根据您的 json 结构,数据是 json 数组,地址和 cmets 也是如此,因此您必须逐步找到这些 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

    【讨论】:

    • 感谢@JRG 的好回答,我目前正在尝试同时学习和编码,我需要在星期一之前完成,任何帮助将不胜感激。现在我正在努力解决 - “解析 JSON 结果 org.json.JSONException 的问题:java.lang.Integer 类型的 app_time 的值 1504620000 无法转换为 JSONObject”我无法理解值 1504620000 是一个 Int ok。 UNIX 格式的 app_time,我试图将它传递下去,这是否意味着我没有正确阅读它?
    • 私人事件 extractFeatureFromJson(String str) { try { JSONObject obj = new JSONObject(str); JSONObject appTime = obj.getJSONArray("data").getJSONObject(0).getJSONObject("app_time"); long timeEvent = appTime.getLong("app_time");
    • 这是正确的,您必须知道要提取什么(int 或 long,以及该值是否适合数据类型的限制或转到更广泛的数据类型)并使用适当的数据类型进行转换或使用 getString、getLong 等 JSONObject 方法。这里是更多信息的链接。 developer.android.com/reference/org/json/JSONObject.html我也会把它添加到我的答案中。
    【解决方案2】:
        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());
    
        }
    

    【讨论】:

      猜你喜欢
      • 2021-10-30
      • 2015-10-19
      • 2015-07-23
      • 2013-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      相关资源
      最近更新 更多