将json解析为字符串时出错

时间:2012-04-10 22:14:44

标签: php android json

enter image description here伙计们我正在尝试将我的Android应用程序连接到php服务器并使用json对数据进行编码。我无法在应用程序上解码它。 请帮忙

public class JsonDemoActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */
     HttpPost httppost;

        StringBuffer buffer;

        HttpResponse response;

        HttpClient httpclient;
        TextView tv;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv=(TextView) findViewById(R.id.textView1);
        Button b=(Button) findViewById(R.id.button1);
        b.setOnClickListener(this);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
         try{

             httpclient=new DefaultHttpClient();

             httppost= new HttpPost("http://10.0.2.2/jsondemo.php"); // make sure the url is correct.



             response=httpclient.execute(httppost);

             HttpEntity he=response.getEntity();

             JSONObject jo=new JSONObject(EntityUtils.toString(he));

             String message=jo.getString("message");
             String from=jo.getString("from");
             String to=jo.getString("to");

             tv.setText("Message "+message+"/n"+"from "+from+"/n"+"to "+to);



             tv.setText("Response from PHP : " + response);

         }catch(Exception e){

             System.out.println("Exception : " + e.getMessage());
                tv.setText(e.getLocalizedMessage());
                System.out.println("Response from php"+response);
         }

    }
}

这是php端代码

<?php

header('Content-Type: application/json');
$obj = new stdClass();

$obj->message="hello";
$obj->from="pratik";
$obj->to="server";

echo json_encode($obj);
?>

我收到的错误无法将json转换为字符串。enter image description here

1 个答案:

答案 0 :(得分:0)

我删除了该行 tv.setText(&#34;来自PHP的响应:&#34; +响应); 从代码。 它终于奏效了。!!!

tv.setText(&#34;消息&#34; +消息+&#34; / n&#34; +&#34;来自&#34; +来自+&#34; / n&#34; +&#34;到&#34; +到); 这被tv.setText覆盖了(&#34;来自PHP的响应:&#34; +响应);