繁体   English   中英

我正在使用另一个SO帖子中的答案,但遇到了JSONArray无法转换为JSONObject的异常。 我该如何解决?

[英]I'm using the answer from another SO post and I'm getting an exception JSONArray cannot be converted to JSONObject. How can I get this resolved?

这是我正在使用的答案如何在Android中使用HttpURLConnection和PHP服务器实现登录

这是我的JSONParser.java:

package com.example.android.simplejson;

import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {

    String charset = "UTF-8";
    HttpURLConnection conn; // Connection
    DataOutputStream wr;    // Write
    StringBuilder result;
    URL urlObj;
    JSONObject jObj = null;
    StringBuilder sbParams;
    String paramsString;

    public JSONObject makeHttpRequest(String url, String method,
                                      HashMap<String, String> params) {

        sbParams = new StringBuilder();
        int i = 0;
        for (String key : params.keySet()) {
            try {
                if (i != 0){
                    sbParams.append("&");
                }
                sbParams.append(key).append("=")
                        .append(URLEncoder.encode(params.get(key), charset));

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            i++;
        }

        if (method.equals("POST")) {
            // request method is POST
            try {
                urlObj = new URL("my_url");

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(true);

                conn.setRequestMethod("POST");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setReadTimeout(10000);
                conn.setConnectTimeout(15000);

                conn.connect();

                paramsString = sbParams.toString();

                wr = new DataOutputStream(conn.getOutputStream());
                wr.writeBytes(paramsString);
                wr.flush();
                wr.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else if(method.equals("GET")){
            // request method is GET

            try {
                urlObj = new URL("my_url");

                conn = (HttpURLConnection) urlObj.openConnection();

                conn.setDoOutput(false);

                conn.setRequestMethod("GET");

                conn.setRequestProperty("Accept-Charset", charset);

                conn.setConnectTimeout(15000);

                conn.connect();

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

        }

        try {
            //Receive the response from the server
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
                Log.d("Response: ", "> " + line); //here you'll get the whole response
            }

            Log.d("JSON Parser", "result: " + result.toString());

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

        conn.disconnect();

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(result.toString());
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON Object
        return jObj;
    }
}

这是我的MainActivity.java的一个片段:

class checkLogin extends AsyncTask<String, String, JSONObject> {
        JSONParser jsonParser = new JSONParser();

        private ProgressDialog pd;

        private static final String LOGIN_URL = "my_url";

        private static final String TAG_SUCCESS = "success";
        private static final String TAG_MESSAGE = "message";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("Attempting login...");
            pd.setIndeterminate(false);
            pd.setCancelable(true);
            pd.show();
        }

        protected JSONObject doInBackground(String... params) {

            try {

                HashMap<String, String> credentials = new HashMap<>();
                credentials.put("username", params[0]);
                credentials.put("password", params[1]);

                Log.d("request", "starting");

                JSONObject json = jsonParser.makeHttpRequest(
                        LOGIN_URL, "POST", credentials);

                if (json != null) {
                    Log.d("JSON result", json.toString());

                    return json;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(JSONObject json) {

            int success = 0;
            String message = "";

            if (pd != null && pd.isShowing()) {
                pd.dismiss();
            }

            if (json != null) {
                Toast.makeText(MainActivity.this, json.toString(),
                        Toast.LENGTH_LONG).show();

                try {
                    success = json.getInt(TAG_SUCCESS);
                    message = json.getString(TAG_MESSAGE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (success == 1) {
                Log.d("Success!", message);
            } else {
                Log.d("Failure", message);
            }
        }
    }
}

它从服务器[{“ AuthStatus”:true,“ AuthMessage”:“这是我的示例消息”,“用户名”:“用户名=&密码=”}“中获取一个JSONArray。

我的问题是JSONArray无法转换为JSONObject。 那么我该如何更改代码以将JSONArray返回为jObj? 我的最终目标是将我的主要活动中的文本设置为[{“ AuthStatus”:true,“ AuthMessage”:“这是我的示例消息”,“ username”:“ username =&password =”}]。

谢谢!

您不能将JSON数组解析为JSON对象。 首先,您必须将有效负载解析为数组,然后从中获取对象。

public JSONObject makeHttpRequest(String url, String method,
    HashMap<String, String> params) {

    // ...

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

    // return JSON Object
    return jObj;
}

请参考以下示例:

String str = {"xyz":[{"name":"apple","email_id":"apple@apple.com"}]};
JSONObject json = JSONObject.fromObject(str);

因此,基本上,您的响应采用JSONArray [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]'格式

应该是这样的地方

{"response": [{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}]}

或简单地

{"AuthStatus":true,"AuthMessage":"This is my sample message","username":"username=&password="}

根据您的喜好。 如果您总是要返回单个JSONObject(可能是由于登录服务响应),则无需使用方括号将其变成JSONArray。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM