android应用程序中jsonObject的空值

时间:2015-05-01 09:37:00

标签: php android json

我昨晚发布了这个问题,但我无法解决我的问题。所以我再次发布此希望会员可以帮助我。谢谢 ! 我有从json对象获取值的问题.json_encode将null字符串返回到android。

Logcat:

05-01 22:36:21.653: D/Create Response(801): {}

05-01 22:36:21.653: W/System.err(801): org.json.JSONException: No value
for success

05-01 22:36:21.663: W/System.err(801):  at

org.json.JSONObject.get(JSONObject.java:354)

05-01 22:36:21.663: W/System.err(801):  at 

org.json.JSONObject.getInt(JSONObject.java:443)

MyPhp.php

<?php


header('Content-type=application/json; charset=utf-8');
$response = array();
// check for required fields
if (isset($_POST['B_Name']) && isset($_POST['Au_Name']) && 
isset($_POST['Pub']) && isset($_POST['Pr']) && 
isset($_POST['B_Genre']))  {

$B_Name = $_POST['B_Name'];
$Au_Name = $_POST['Au_Name'];
$Pub = $_POST['Pub'];
$Pr = $_POST['Pr'];
$B_Genre = $_POST['B_Genre'];

// include db connect class
require_once( __DIR__ . '/android/db_connect.php');

// connecting to db
$db = new DB_CONNECT();

// mysql inserting a new row
$result = mysql_query("INSERT INTO products(Book_Name, Author_Name, Book_Genre, Price, Publication) VALUES('$B_Name', '$Au_Name', '$B_Genre', '$Pr', '$Pub')");

// check if row inserted or not
if ($result) {
    // successfully inserted into database
    $response["success"] = 1;
    $response["message"] = "Product successfully created.";


 $encoded_rows = array_map('utf8_encode', $response);
   echo json_encode($encoded_rows);
} else {
    // failed to insert row
    $response["success"] = 0;
    $response["message"] = "Oops! An error occurred.";

  $encoded_rows = array_map('utf8_encode', $response);
   echo json_encode($encoded_rows);
     }
} else {

  $response["success"] = 0;
  $response["message"] = "Required field(s) is missing";
  $encoded_rows = array_map('utf8_encode', $response);
  echo json_encode($encoded_rows);
  }

这是我的doInBackground:

        String B_Name = BookName.getText().toString();
        String Au_Name = AuthorName.getText().toString();
        String Pub = Publication.getText().toString();
        String Pr = Price.getText().toString();
        String B_Genre = BookGenre.getText().toString();


        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("B_Name", B_Name));
        params.add(new BasicNameValuePair("Au_Name", Au_Name));
        params.add(new BasicNameValuePair("Pub", Pub));
        params.add(new BasicNameValuePair("Pr", Pr));
        params.add(new BasicNameValuePair("B_Genre", B_Genre));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                Intent i = new Intent(getApplicationContext(),    
       MainActivity.class);
                startActivity(i);
                finish();


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

编辑:

Jsonparser:

public class JSONParser  {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    // Making HTTP request
    try {

        // check for request method
        if(method.equals("POST")){

            HttpClient httpclient = getNewHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpclient.execute(httpPost);
            if(httpResponse != null){
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
            }

        }else if(method.equals("GET")){
            // request method is GET
            HttpClient httpclient = getNewHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpclient.execute(httpGet);
            if(httpResponse != null){
            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();
        sb.append("{");
        sb.append(StringUtils.substringBeforeLast(StringUtils.substringAfter(json, "{"), "}"));
        sb.append("}");
        String line = null;
        if(reader != 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;

}


public HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
 }
}

Sale.java

public class Sale extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText BookName;
EditText AuthorName;
EditText Publication;
EditText Price;
EditText BookGenre;

// url to create new product
private static String url_create_product = "https://5.144.130.36:2083/android/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    setContentView(R.layout.sale);

    BookName = (EditText) findViewById(R.id.BookName);
    AuthorName = (EditText) findViewById(R.id.AuthorName);
    Publication = (EditText) findViewById(R.id.Publication);
    Price = (EditText) findViewById(R.id.Price);
    BookGenre = (EditText) findViewById(R.id.BookGenre);


    Button confirm = (Button) findViewById(R.id.Confirm);


    confirm.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            new CreateNewBook().execute();      
        }


    });
}

类CreateNewBook扩展了AsyncTask {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Sale.this);
        pDialog.setMessage("?? ??? ??? ???? ...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    protected String doInBackground(String... args) {
         Sale.this.runOnUiThread(new Runnable() {
                public void run() {
        String B_Name = BookName.getText().toString();
        String Au_Name = AuthorName.getText().toString();
        String Pub = Publication.getText().toString();
        String Pr = Price.getText().toString();
        String B_Genre = BookGenre.getText().toString();


        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("B_Name", B_Name));
        params.add(new BasicNameValuePair("Au_Name", Au_Name));
        params.add(new BasicNameValuePair("Pub", Pub));
        params.add(new BasicNameValuePair("Pr", Pr));
        params.add(new BasicNameValuePair("B_Genre", B_Genre));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

        // check log cat fro response
        Log.d("Create Response", json.toString());

        // check for success tag
        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(i);
                finish();


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

                }
     }); 

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String result) {
        // dismiss the dialog once done
        pDialog.cancel();
        /*
        if (result !=null && result.equals("1"))
            Toast.makeText(getApplicationContext(), "submit ", Toast.LENGTH_LONG).show();
    */
    }

  }

}

1 个答案:

答案 0 :(得分:0)

试试这个解析器:

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if (method == "POST") {
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);              
                httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if (method == "GET") {
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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"), 10000);
            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;

    }
}

如果您使用$encoded_rows = array_map('utf8_encode', $response); 变量类型successs从INTEGER更改为STRING。

例如,$encoded_rows = array_map('utf8_encode', $response);的响应如下所示:

{"success":"0"}

,只有echo json_encode($response);

{"success":0}

所以,我认为,这:int success = json.getInt(TAG_SUCCESS);无法工作。

不要使用array_map('utf8_encode', $response);或在Java中使用此行:

String success = json.getString(TAG_SUCCESS);