Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java JSON值解析Android Studio_Java_Android_Json - Fatal编程技术网

Java JSON值解析Android Studio

Java JSON值解析Android Studio,java,android,json,Java,Android,Json,我目前正在学习如何在Android Studio上创建应用程序,并一直在尝试与服务器建立JSON连接,从服务器带回信息并在我的应用程序中显示。我已经能够按照逻辑说明进行连接,但是我不清楚我面临的错误以及如何解决它。我将在这里展示我为建立JSON连接而构造的两个类以及显示的错误。当我运行模拟器时,它只是说,unfotunaley,JSONconnection应用程序已经停止工作 谢谢你的帮助 logcat上出现错误,出现异常 04-08 08:10:23.860 1656-1656/com.

我目前正在学习如何在Android Studio上创建应用程序,并一直在尝试与服务器建立JSON连接,从服务器带回信息并在我的应用程序中显示。我已经能够按照逻辑说明进行连接,但是我不清楚我面临的错误以及如何解决它。我将在这里展示我为建立JSON连接而构造的两个类以及显示的错误。当我运行模拟器时,它只是说,unfotunaley,JSONconnection应用程序已经停止工作

谢谢你的帮助

logcat上出现错误,出现异常

04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection E/JSON Parser﹕ Error parsing data org.json.JSONException: Value [{"id":"170656","RatingValue":"5","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Cheeky Coffee Co","Longitude":"-2.240435","RatingDate":"2014-02-06","AddressLine1":"Unit 10, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"171710","RatingValue":"3","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Nando's","Longitude":"-2.240435","RatingDate":"2013-01-17","AddressLine1":"Unit 3, The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"172780","RatingValue":"4","DistanceKM":"0.0483604565731744","PostCode":"M1 5QS","Latitude":"53.472442","BusinessName":"Zouk Tea Bar & Grill","Longitude":"-2.240435","RatingDate":"2010-06-11","AddressLine1":"Unit 5 The Quadrangle","AddressLine2":"Chester Street","AddressLine3":"Manchester"},{"id":"170593","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Caffe Nero","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"8A Oxford Road","AddressLine3":"Manchester"},{"id":"171089","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Greggs","Longitude":"-2.23997","RatingDate":"2011-01-18","AddressLine1":"","AddressLine2":"10 Oxford Road","AddressLine3":"Manchester"},{"id":"171185","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Holiday Inn Express","Longitude":"-2.23997","RatingDate":"2011-03-17","AddressLine1":"","AddressLine2":"2-4 Oxford Road","AddressLine3":"Manchester"},{"id":"171382","RatingValue":"1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Kukoos","Longitude":"-2.23997","RatingDate":"2013-11-18","AddressLine1":"","AddressLine2":"12a Oxford Road","AddressLine3":"Manchester"},{"id":"171404","RatingValue":"-1","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Ladbrokes","Longitude":"-2.23997","RatingDate":"2010-11-09","AddressLine1":"","AddressLine2":"10B Oxford Road","AddressLine3":"Manchester"},{"id":"172281","RatingValue":"5","DistanceKM":"0.0858826413670853","PostCode":"M1 5QA","Latitude":"53.472901","BusinessName":"Subway","Longitude":"-2.23997","RatingDate":"2013-10-09","AddressLine1":"","AddressLine2":"12 Oxford Road","AddressLine3":"Manchester"},{"id":"171119","RatingValue":"5","DistanceKM":"0.100210503082758","PostCode":"M1 5GE","Latitude":"53.47208","BusinessName":"H & M Convenience Store","Longitude":"-2.241442","RatingDate":"2010-09-16","AddressLine1":"Student Village","AddressLine2":"Lower Chatham Street","AddressLine3":"Manchester"}] of type org.json.JSONArray cannot be converted to JSONObject
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection D/AndroidRuntime﹕ Shutting down VM
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb2cbdb20)
04-08 08:10:23.860    1656-1656/com.example.adam.jsonconnection E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.adam.jsonconnection, PID: 1656
JSONParser类

   package com.example.adam.jsonconnection;

import android.util.Log;

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 java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;


public class JSONParser {

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


    // constructor
    public JSONParser() {
    }
    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            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("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jObj;
    }
}
主要活动类

    package com.example.adam.jsonconnection;

import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

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


public class MainActivity extends ActionBarActivity {



    //URL to get JSON Array
    private static String url = "";

    //JSON Node Names
    private static final String TAG_NEAREST = "nearest";
    private static final String TAG_BusinessName = "BusinessName";

    JSONArray nearest = null;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();

        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        try {
            // Getting JSON Array
            nearest = json.getJSONArray(TAG_NEAREST);
            JSONObject c = nearest.getJSONObject(0);

            // Storing  JSON item in a Variable
            String businessName = c.getString(TAG_BusinessName);


            //Importing TextView
            final TextView BusinessNameText = (TextView)findViewById(R.id.BusinessName);

            //Set JSON Data in TextView
            BusinessNameText.setText(businessName);

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

您有一个
JSONArray
,您正试图用它创建一个
JSONObject
对象

只需将代码更改为:

try {
    jObj = new JSONArray(json);
} catch (JSONException e) {
    Log.e("JSON Parser", "Error parsing data " + e.toString());
}

或者编辑您的响应,使其成为json对象。

您的json是来自根的数组,因此您必须更改为:

JSONObject json = jParser.getJSONFromUrl(url);

并从
getJSONFromUrl

// try parse the string to a JSON object
try {
   jObj = new JSONArray(json);
} catch (JSONException e) {
   Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
我建议您使用:

jsonObject.optString("your_key");
而不是:

jsonObject.getString("your_key");

这将自动处理日志
org.json.JSONArray中可能出现的“null”值

无法转换为JSONObject
这是一种可以在UI线程中运行服务器通信的线程策略吗?我不建议这样做。看看loopj,它使服务器的通信方式,更容易!感谢您在这里给我的帮助,我现在有另一个错误,我已经将JSONParser类中的代码更改为您所说的,将主活动中的代码更改为
nearest=json.getJSONArray(Integer.parseInt(TAG_nearest))标记_NEAREST
(即
“NEAREST”
)?
jsonObject.getString("your_key");