简体   繁体   English

org.json.JSONObject无法转换为JSONArray

[英]org.json.JSONObject cannot be converted to JSONArray

I am unable to display the values which are coming in the form of json response 我无法显示以json响应形式出现的值

And I am failed to convert these values and display it the textView.. 我无法转换这些值并将其显示为textView ..

My json reponse is : 我的json响应是:

{"calculate":{"persons":"148429","cost":25232.93}}

And My main Activity java file is : 我的主要Activity java文件是:

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

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


public class MainActivity extends ActionBarActivity {
    TextView uid;
    TextView name1;
    TextView email1;
    Button Btngetdata;
    //URL to get JSON Array
    private static String url = "http://urls.p/GetData.php?";
    //JSON Node Names
    private static final String TAG_USER = "calculate";
    //private static final String TAG_ID = "id";
    private static final String TAG_NAME = "persons";
    private static final String TAG_EMAIL = "cost";
    JSONArray user = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Btngetdata = (Button)findViewById(R.id.getdata);
        Btngetdata.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new JSONParse().execute();
            }
        });
    }
    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            uid = (TextView)findViewById(R.id.uid);
            name1 = (TextView)findViewById(R.id.name);
            email1 = (TextView)findViewById(R.id.email);
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();
            // Getting JSON from URL
            JSONObject json = jParser.getJSONFromUrl(url);
            return json;
        }
        @Override
        protected void onPostExecute(JSONObject json) {
            pDialog.dismiss();

            for (int i = 0; i < json.length(); i++) {
                try {
                    //JSONObject c = json.getJSONObject(i);
                    // Getting JSON Array

                   JSONObject c = user.getJSONObject(i);
                    // Storing  JSON item in a Variable
                    // String id = c.getString(TAG_ID);
                    //System.out.println();
                    String name = c.getString(TAG_NAME);
                    // System.out.println(name);
                    String email = c.getString(TAG_EMAIL);
                    //System.out.println(email);
                    //Set JSON Data in TextView
                    //uid.setText(id);
                    name1.setText(name);
                    email1.setText(email);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

And JSON Parser Class: 和JSON解析器类:

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;

/**
 * Created by Admin on 09-04-2015.
 */
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;
    }
}

activity_main.xml file activity_main.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/uid"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ff000000" />
    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_alignRight="@+id/getdata"
        android:layout_alignEnd="@+id/getdata"
        android:textColor="#ff000000" />
    <TextView
        android:id="@+id/uid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentTop="true"
        android:textColor="#ff000000"  />

    <Button
        android:id="@+id/getdata"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="23dp"
        android:text="Get Data"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

And the logcat: 和logcat:

04-09 09:04:34.904    1170-1170/com.example.health.myapplication W/System.err﹕ org.json.JSONException: Value {"cost":25232.93,"persons":"148429"} at calculate of type org.json.JSONObject cannot be converted to JSONArray

Your json is a JSONObject not a JSONArray. 你的json是JSONObject而不是JSONArray。

{ represents JSONObject node {表示JSONObject节点

[ represents JSONArray node [代表JSONArray节点

So having this for (int i = 0; i < json.length(); i++) { is wrong 所以有这个for (int i = 0; i < json.length(); i++) {是错误的

In onPostExecute onPostExecute

JSONObject calculate = json.optJSONObject("calculate");
String person = calculate.optString("persons");
String cost = calculate.optString("cost");

try this 尝试这个

public JSONObject getJSONFromUrl(String url) {

    String response="";
        // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        try {

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            response = httpclient.execute(httppost,
                           responseHandler);

        }
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (SocketTimeoutException e) {

        //"Sorry, network error", "");
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (Exception e) {
        System.out.println(e);
    }
    try {

        json = new JSONObject(response.toString());

        JSONObject subobject = new JSONObject(
                                json.getString("calculate"));

        String persons= (subobject.getString("persons"));
        String cost= (subobject.getString("cost"));

    }
    catch (JSONException e) {

        System.out.println("exception");
        exceptionflag = 0;

    }
}

-TOtaly agree with above answer Person is fetching Jsonobject using Jsonarray Which is totaly wrong. 以上回答人是取-TOtaly同意Jsonobject使用Jsonarray这是完全以错误的。 -Here you are only having a single JsonObject Named calculate - 这里只有一个JsonObject命名calculate

-Which is fetched by using :- - 使用以下内容获取: -

JSONObject jsobobj = json.optJSONObject("calculate");

-And other strings are values of above object so can be fetched by using. - 其他字符串是上述对象的值,因此可以通过使用获取。

String Firststring = calculate.optString("persons");
String Seconstring = calculate.optString("cost");

-THanks! -谢谢!

 JSONObject jsonObject = new JSONObject("your json String will be here");
 JSONObject jsonObject = jsonObject.getJSONObject("calculate");
String persons = jsonObject.getString("persons");
String cost = jsonObject.getString("cost");

In your postExecute method 在你的postExecute方法中
Replace JSONObject c = user.getJSONObject(i); 替换JSONObject c = user.getJSONObject(i);
With JSONObject c = json.getJSONObject(i); 使用JSONObject c = json.getJSONObject(i);

Because user is a jsonArray which is never initialized, 因为user是一个永远不会被初始化的jsonArray,
and you are getting your json in json variable here in 你在这里得到json变量的json变量
doInBackground method JSONObject json = jParser.getJSONFromUrl(url); doInBackground方法JSONObject json = jParser.getJSONFromUrl(url);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法将org.json.JSONObject类型的数据转换为JSONArray - Data of type org.json.JSONObject cannot be converted to JSONArray 类型为org.json.JSONObject的响应无法转换为JSONArray - at response of type org.json.JSONObject cannot be converted to JSONArray at 类型 org.json.JSONObject 的数据无法转换为 JSONArray - at data of type org.json.JSONObject cannot be converted to JSONArray 错误org.json.JSONObject无法转换为JSONArray - error org.json.JSONObject cannot be converted to JSONArray 值类型 org.json.JSONObject 无法转换为 JSONArray - Value type org.json.JSONObject cannot be converted to JSONArray 解析JSON数组时,获取异常“ org.json.JSONObject类型的答案无法转换为JSONArray” - Getting exception “ at answer of type org.json.JSONObject cannot be converted to JSONArray” while parsing JSON array 在Android中解析JSON响应“无法将org.json.JSONObject类型的响应转换为JSONArray” - Parse JSON response in android “response of type org.json.JSONObject cannot be converted to JSONArray” 我有一个错误:类型 org.json.JSONObject 无法转换为 JSONArray - I have an error : type org.json.JSONObject cannot be converted to JSONArray org.json.JSONException:值 {“storeid0”:[“1535”],“storeid1”:[“1862”]} 类型为 org.json.JSONObject 的 idddsss 无法转换为 JSONArray - org.json.JSONException: Value {“storeid0”:[“1535”],“storeid1”:[“1862”]} at idddsss of type org.json.JSONObject cannot be converted to JSONArray org.json.JSONArray无法转换为JSONObject - org.json.JSONArray cannot be converted to JSONObject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM