将 android 连接到移动数据库时出现 JSONArray 错误

发布于 2024-12-19 06:59:12 字数 2900 浏览 0 评论 0原文

我正在尝试使用 android 连接到我的在线数据库。在遵循教程后,我想出了这段代码:

package com.example.helloandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class HelloAndroid extends Activity {
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.4/~jasptack/Software%20engineering/connector.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            }catch(Exception e){
                Log.e("log_tag", "Error in http connection"+e.toString());
           }

        //convert response to string
        try{
              BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
               sb = new StringBuilder();
               sb.append(reader.readLine() + "\n");
               String line="0";
               while ((line = reader.readLine()) != null) {
                              sb.append(line + "\n");
               }
               is.close();
               result=sb.toString();
               }catch(Exception e){
                      Log.e("log_tag", "Error converting result "+e.toString());
               }
      //parse json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","x-co: "+json_data.getInt("x-coordinaat")+
                                ", straat: "+json_data.getString("straat")
                        );
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
    }
}

当我执行此代码时,出现以下错误: 12-04 23:25:07.711:E / log_tag(353):解析数据org.json.JSONException时出错:值

有人可以帮忙吗?谢谢!

I am trying to connect to my online database with android. After following a tutorial I came up with this piece of code:

package com.example.helloandroid;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.*;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class HelloAndroid extends Activity {
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb=null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://192.168.1.4/~jasptack/Software%20engineering/connector.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            }catch(Exception e){
                Log.e("log_tag", "Error in http connection"+e.toString());
           }

        //convert response to string
        try{
              BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
               sb = new StringBuilder();
               sb.append(reader.readLine() + "\n");
               String line="0";
               while ((line = reader.readLine()) != null) {
                              sb.append(line + "\n");
               }
               is.close();
               result=sb.toString();
               }catch(Exception e){
                      Log.e("log_tag", "Error converting result "+e.toString());
               }
      //parse json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","x-co: "+json_data.getInt("x-coordinaat")+
                                ", straat: "+json_data.getString("straat")
                        );
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
    }
}

When I execute this, I get the following error:
12-04 23:25:07.711: E/log_tag(353): Error parsing data org.json.JSONException: Value

Can anybody help with this? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

慵挽 2024-12-26 06:59:12

如果 JSON 字符串格式错误,就会发生这种情况。确保 String result 是有效的 JSONArray(应以“[”开头)。另外,您可以尝试将 result 映射到 JSONObject。如果这些都正常,则 JSONArray 内的元素之一格式错误。

This happens if the JSON string is malformed. Make sure that the String result is a valid JSONArray (Should start with '['). Also, you can try mapping result to a JSONObject instead. If these are fine, one of the elements inside the JSONArray is malformed.

那请放手 2024-12-26 06:59:12

我曾经尝试解析我的 Web 服务返回的 JSON 字符串。这是我所做的:

我从网络服务得到的响应是:

{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

为了解析我做了以下操作:

      JSONObject jsonobject = new JSONObject(result);
      JSONArray array = jsonobject.getJSONArray("checkrecord"); 
      int max = array.length();
      for (int j = 0; j < max; j++) 
   {
      JSONObject obj = array.getJSONObject(j);
      JSONArray names = obj.names();

     for (int k = 0; k < names.length(); k++) 
   {
      String name = names.getString(k);
      String value= obj.getString(name);  

   }

我的 JSONObject 看起来像这样:

{"Table1":[],"checkrecord":[{"missed":34,"attended":12,"percentage":40,"rollno":"abc2"}]}

这就是 @500865 正在尝试的建议。我刚刚给了你一个代码示例。首先检查您的结果并确定其是否有效。还要检查 JSONArray 结果。
如果可能的话,将其发布到这里。

希望它有帮助

干杯

I once tried parsing a JSON String returned by my web service. Here is what I did:

The response I got from the web service was:

{"checkrecord":[{"rollno":"abc2","percentage":40,"attended":12,"missed":34}],"Table1":[]}

In order to parse I did the following:

      JSONObject jsonobject = new JSONObject(result);
      JSONArray array = jsonobject.getJSONArray("checkrecord"); 
      int max = array.length();
      for (int j = 0; j < max; j++) 
   {
      JSONObject obj = array.getJSONObject(j);
      JSONArray names = obj.names();

     for (int k = 0; k < names.length(); k++) 
   {
      String name = names.getString(k);
      String value= obj.getString(name);  

   }

My JSONObject looks like this:

{"Table1":[],"checkrecord":[{"missed":34,"attended":12,"percentage":40,"rollno":"abc2"}]}

This is what the @500865 was trying to suggest. I just gave a code sample to you. Check your result first and determine whether it is valid. Also check JSONArray result.
If possible post it over here.

Hope it helps

Cheers

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文