JSONException:在Android中无法将String转换为JSON数组

时间:2014-03-17 19:57:57

标签: php android json

我一直在研究各种示例代码,以了解JSON的工作原理。以下代码在logcat中给出错误,指出“String无法转换为JSON数组”

MainActivity.java

package com.example.jsontry;
import java.io.*;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.*;
import org.json.*;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity{
    ArrayList<Person> arrayofWebData=new ArrayList<Person>();
    class Person{
        //public String person_id;
        public String name;
        public String birthday;
        public String favourite_color;
    }
    FancyAdapter aa=null;
    static ArrayList<String> resultRow;

    public void onCreate(Bundle savedInstanceState){
        try{
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

                StrictMode.setThreadPolicy(policy); 
            String result="";
            try{
                HttpClient httpclient=new DefaultHttpClient();
                HttpPost httppost=new HttpPost("http://192.168.43.77/test/jsontest.php");
                HttpResponse response=httpclient.execute(httppost);
                HttpEntity entity=response.getEntity();
                InputStream webs= entity.getContent();
                try{
                    BufferedReader reader= new BufferedReader(new InputStreamReader(webs,"iso-8859-1"),8);
                    StringBuilder sb= new StringBuilder();
                    String line=null;
                    while((line=reader.readLine())!=null){
                        sb.append(line+"\n");
                    }
                    webs.close();
                    result=sb.toString();
                }catch(Exception e){
                    Log.e("log_tag","Error converting result"+e.toString());
                }

            }catch(Exception e){
                Log.e("log_tag","Error in http connection"+e.toString());
            }
            try{
                JSONArray jArray=new JSONArray(result);
                for(int i=0;i<jArray.length();i++)
                {
                    JSONObject json_data=jArray.getJSONObject(i);
                    Person resultRow=new Person();
                    //resultRow.person_id=json_data.getString("person_id");
                    resultRow.name=json_data.getString("name");
                    resultRow.favourite_color=json_data.getString("favourite_color");
                    resultRow.birthday=json_data.getString("birthday");
                    arrayofWebData.add(resultRow);

                }
            }
            catch(JSONException e){
                Log.e("log_tag","Error parsing data"+e.toString());
            }
            ListView myListView =(ListView)findViewById(R.id.myListView);
            aa=new FancyAdapter();
            myListView.setAdapter(aa);
        }
        catch(Exception e){
            Log.e("ERROR","ERROR IN CODE"+e.toString());
            e.printStackTrace();
        }
    }
    class FancyAdapter extends ArrayAdapter<Person>{
        FancyAdapter(){
            super(MainActivity.this,android.R.layout.simple_list_item_1,arrayofWebData);
        }
        public View getView(int position,View convertView, ViewGroup parent){
            ViewHolder holder;
            if(convertView==null){
                LayoutInflater inflater=getLayoutInflater();
                convertView=inflater.inflate(R.layout.row, null);
                holder=new ViewHolder(convertView);
                convertView.setTag(holder);
            }
            else{
                holder=(ViewHolder)convertView.getTag();
            }
            holder.populateFrom(arrayofWebData.get(position));
            return(convertView);
        }
    }
    class ViewHolder{
        public TextView name=null;
        public TextView birthday=null;
        public TextView favourite_color=null;
        ViewHolder(View row){
            name=(TextView)row.findViewById(R.id.name);
            birthday=(TextView)row.findViewById(R.id.birthday);
            favourite_color=(TextView)row.findViewById(R.id.favourite_color);
        }
        void populateFrom(Person r){
            name.setText(r.name);
            birthday.setText(r.birthday);
            favourite_color.setText(r.favourite_color);
        }
    }
}

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView 
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#EE0000" />
    <TextView 
        android:id="@+id/birthday"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#00EE00" />
    <TextView 
        android:id="@+id/favourite_color"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#0000EE" />


</LinearLayout>

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@+id/myListView"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent" >
        </ListView>
        </LinearLayout>

jsontest.php

<?php
$host="localhost"
$dbname="androidhive"
$uname="root"
$pass="karvig"
$con=mysql_connect($host,$uname,$pass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$query="SELECT (name,price,description) FROM products";
$sth=mysql_query($query);
if(mysql_errno()){
    header("HTTP/1.1 500 Internal Server Error");
    echo $query.'\n';
    echo mysql_error();
}
else
{
    $rows=array();
    while($r=mysql_fetch_assoc($sth)){
        $rows[]=$r;
    }
    print json_encode($rows);
}
?>

logcat的

03-18 01:16:38.276: E/log_tag(11564): Error parsing dataorg.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

1 个答案:

答案 0 :(得分:0)

您应首先为您要发送的JSON对象设置一个名称,这样您就可以拥有一个对象数组而不仅仅是数据,然后创建一个JSON对象,以便您可以将其转换为接收器中的JSON数组,像这样:

json = new JSONObject(result);
JSONArray jArray= Json.getJSONArray("SomeObject");    
try{
                for(int i=0;i<jArray.length();i++)
                {
                    JSONObject json_data=jArray.getJSONObject(i);
                    Person resultRow=new Person();
                    //resultRow.person_id=json_data.getString("person_id");
                    resultRow.name=json_data.getString("name");
//etc