dongpao2871 2014-09-06 10:17
浏览 427
已采纳

解析数据时出错org.json.JSONException:Value String无法转换为JSONArray

Here is list activity.

List Activity:

public class ListDataActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_listview);

    url = "http://xxx.xx.x.xxx/index.php";

    Bundle c = getIntent().getExtras();
    blo = c.getString("blood");

    new ProgressTask(ListDataActivity.this).execute();

}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

}

class ProgressTask extends AsyncTask<String, Void, Boolean> {

    ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();

    ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    {
        if (conMgr.getActiveNetworkInfo() != null
                && conMgr.getActiveNetworkInfo().isAvailable()
                && conMgr.getActiveNetworkInfo().isConnected()) {
        } else {
            Toast.makeText(getApplicationContext(),
                    "INTERNET CONNECTION NOT PRESENT", Toast.LENGTH_SHORT)
                    .show();
            startActivity(new Intent(ListDataActivity.this,
                    MainActivity.class));
        }

    }


    public ProgressTask(ListActivity activity) {
        context = activity;
    }

    private Context context;

    protected void onPreExecute() {

    }

    @Override
    protected void onPostExecute(final Boolean success) {
    ListAdapter adapter = new SimpleAdapter(context, jsonlist,
                R.layout.row_listitem, new String[] { name, Category },
                new int[] { R.id.vehicleType, R.id.vehicleColor }) {

            @Override
            public View getView(int position, View convertView,
                    ViewGroup parent) {

                if (convertView == null) {

                    // This a new view we inflate the new layout

                    LayoutInflater inflater = (LayoutInflater) context
                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                    convertView = inflater.inflate(R.layout.row_listitem,
                            null);
                }

                // TODO Auto-generated method stub
                if (position % 2 == 1) {

                    convertView.setBackgroundColor(Color.rgb(120, 151, 66));
                } else {
                    convertView.setBackgroundColor(Color.rgb(86, 107, 129));
                }
                return super.getView(position, convertView, parent);
            }
        };

        setListAdapter(adapter);

        lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
            }
        });
    }

    protected Boolean doInBackground(final String... args) {
            url = url + "?blo_name=" + blo;
        Log.d("", url);

        baseAdapter jParser = new baseAdapter();

        JSONArray json = jParser.getJSONFromUrl(url);

        if (json != null) {
            for (int i = 0; i < json.length(); i++) {

                try {
                    JSONObject c = json.getJSONObject(i);

                    String vtype = c.getString(name);
                    String vfuel = c.getString(Category);

                    HashMap<String, String> map = new HashMap<String, String>();

                    // Add child node to HashMap key & value
                    map.put(name, vtype);
                    map.put(Category, vfuel);

                    jsonlist.add(map);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;

    }

Base Adapter class:

public class baseAdapter {

static InputStream iStream = null;
static JSONArray jarray = null;
static String json = "";

public baseAdapter() {
}

public JSONArray getJSONFromUrl(String url) {

    StringBuilder builder = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) {
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } else {
            Log.e("==>", "Failed ");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Parse String to JSON object
    try {

        jarray = new JSONArray(builder.toString());

    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jarray;

}

php:

if(isset($_POST['blo_name'])){
$str = $_POST['blo_name'];
$sql = "SELECT * FROM blood_group where Category IN ($str)";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))  
$output[]=$row;
print(json_encode($output));
mysql_close();
}

My Question is, I an trying to parse bol string, it have value like bol="'B-','O-'"; while I parse this type of value it didn't show results and gives the logcat.

logcat:

Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

While I parse simple value like "B,O"and change in DB it give me result fine. But, I need to parse that value. Pplease, help me out. Thank You

  • 写回答

2条回答 默认 最新

  • douxian1939 2014-09-06 13:52
    关注

    As you said that you are unable to parse the json string which is like "'B-','O-'" but you can successfully parse the string like "B,O".

    It is due to the fact the single quote (') is considered as a special character for json and you may want to escape it like \' in your string before you parse it.

    For more details refer : How to escape special characters in building a JSON string?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献