问题描述
我有问题的字符串不能转换为JSONObject.Anyone可以帮助解决这个问题?谢谢,非常AP preciate帮助。
< PHP
的mysql_connect(localhost的,测试,);
mysql_select_db(测试);
$响应=阵列();
$全称= $ _ POST [全名];
$结果= mysql_query(选择全名,联系人,DATE_FORMAT(reserveDate,'%E-%C-%Y')reserveDate,
DATE_FORMAT(reserveTime,'%H:%I%P')reserveTime,
PAX,tableNumber
利用储备内连接的客户(的customerID)
其中,全名= $全名);
如果(mysql_num_rows($结果)大于0){
$响应[储备] =阵列();
而($行= mysql_fetch_array($结果)){
//临时用户阵
$ RESERV =阵列();
$ RESERV [全名] = $行[全名];
$ RESERV [联系] = $行[联系];
$ RESERV [reserveDate] = $行[reserveDate];
$ RESERV [reserveTime] = $行[reserveTime];
$ RESERV [百富] = $行[百富]。
$ RESERV [tableNumber] = $行[tableNumber];
//推单一产品到最终响应数组
array_push($响应[RESERV],$ RESERV);
}
// 成功
$响应[成功] = 1;
//呼应JSON响应
回声json_en code($响应);
} 其他 {
$响应[成功] = 0;
$响应[信息] =找不到用户;
//回声没有用户JSON
回声json_en code($响应);
}
?>
JSONPARSER类
包com.example.easy;
进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;
进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONException;
进口org.json.JSONObject;
进口android.util.Log;
公共类JSONParser {
静态的InputStream是= NULL;
静态的JSONObject jObj = NULL;
静态JSON字符串=;
//构造
公共JSONParser(){
}
//功能得到URL JSON
//通过HTTP POST或GET方法
公众的JSONObject makeHtt prequest(URL字符串,字符串的方法,
名单<的NameValuePair> PARAMS){
//使HTTP请求
尝试 {
//检查请求的方法
如果(方法==POST){
//请求方法是POST
// defaultHttpClient
DefaultHttpClient的HttpClient =新DefaultHttpClient();
HttpPost httpPost =新HttpPost(URL);
httpPost.setEntity(新UrlEn codedFormEntity(PARAMS));
HTT presponse HTT presponse = httpClient.execute(httpPost);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
}否则,如果(方法==GET){
//请求方法是GET
DefaultHttpClient的HttpClient =新DefaultHttpClient();
字符串中的paramString = URLEn codedUtils.format(PARAMS,UTF-8);
网址+ =? +中的paramString;
HTTPGET HTTPGET =新HTTPGET(URL);
HTT presponse HTT presponse = httpClient.execute(HTTPGET);
HttpEntity httpEntity = HTT presponse.getEntity();
是= httpEntity.getContent();
}
}赶上(UnsupportedEncodingException E){
e.printStackTrace();
}赶上(ClientProtocolException E){
e.printStackTrace();
}赶上(IOException异常E){
e.printStackTrace();
}
尝试 {
的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
是,ISO-8859-1),8);
StringBuilder的SB =新的StringBuilder();
串线= NULL;
而((行= reader.readLine())!= NULL){
sb.append(行+\ N);
}
// JSON = sb.toString();
。JSON = sb.toString()子(0,sb.toString()长度() - 1);
的System.out.println(jsonstring =+ JSON);
is.close();
}赶上(例外五){
Log.e(缓冲区错误,转换的结果错误+ e.toString());
}
//尝试解析字符串到一个JSON对象
尝试 {
jObj =新的JSONObject(JSON);
}赶上(JSONException E){
Log.e(JSON解析器,错误分析数据+ e.toString());
}
//返回JSON字符串
返回jObj;
}
}
有错误发生在ReserveInfo类。得到这个错误的价值。
包com.example.easy;
进口的java.util.ArrayList;
进口java.util.Arrays中;
进口java.util.LinkedHashSet;
进口的java.util.List;
进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;
进口android.app.Activity;
进口android.app.AlertDialog;
进口android.app.ProgressDialog;
进口android.content.DialogInterface;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.ArrayAdapter;
进口android.widget.AutoCompleteTextView;
进口android.widget.Button;
进口android.widget.ScrollView;
进口android.widget.TextView;
进口android.widget.Toast;
公共类CUSTNAME扩展活动实现OnClickListener {
TextView的custinfo2,lblempty2;
按钮btnsearch1;
TextView的custinfo,lblempty;
滚动型svcustdetails,svreserve;
AutoCompleteTextView txtcustname;
串联系人[];
INT ARRAYSIZE;
私人ProgressDialog pDialog;
JSONParser jParser =新JSONParser();
JSONParser jParser2 =新JSONParser();
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_RESERV =RESERV;
私有静态最后弦乐TAG_FULLNAME =全名;
私有静态最后弦乐TAG_CONTACT =接触;
私有静态最后弦乐TAG_DATE =reserveDate;
私有静态最后弦乐TAG_TIME =reserveTime;
私有静态最后弦乐TAG_PAX =百富;
私有静态最后弦乐TAG_TABLE =tableNumber;
JSONArray RESERV = NULL;
JSONArray reserv2 = NULL;
的JSONObject json2;
字符串contactno;
公共无效的onCreate(包savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.custname);
btnsearch1 =(按钮)findViewById(R.id.btnsearch);
svcustdetails =(滚动型)findViewById(R.id.svcustdetails);
svreserve =(滚动型)findViewById(R.id.svreserve);
custinfo2 =(TextView中)findViewById(R.id.custinfo2);
txtcustname =(AutoCompleteTextView)findViewById(R.id.txtcustname);
txtcustname =(AutoCompleteTextView)findViewById(R.id.txtcustname);
btnsearch1 =(按钮)findViewById(R.id.btnsearch1);
lblempty2 =(TextView中)findViewById(R.id.lblempty2);
新LoadContact()执行()。
btnsearch1.setOnClickListener(新OnClickListener(){
公共无效的onClick(最终查看V){
如果(txtcustname.getText()。的toString()。equalsIgnoreCase()){
Toast.makeText(Custname.this,请输入客户名称,Toast.LENGTH_SHORT).show();
}其他{
复位();
新ReserveInfo()执行()。
}
}
});
}
类LoadContact扩展的AsyncTask<字符串,字符串,字符串> {
@覆盖
在preExecute保护无效(){
super.on preExecute();
}
保护字符串doInBackground(字符串参数... args){
名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
JSONObject的JSON = jParser.makeHtt prequest(http://10.0.2.2/Laicamproject/checkName.php,GET,则params);
//检查日志猫JSON效应初探
Log.d(全名,json.toString());
联系方式=新的String [ARRAYSIZE]
尝试 {
INT成功= json.getInt(TAG_SUCCESS);
如果(成功== 1){
RESERV = json.getJSONArray(TAG_RESERV);
ARRAYSIZE = reserv.length();
联系方式=新的String [ARRAYSIZE]
对于(INT一= 0; A< ARRAYSIZE; A ++){
JSONObject的C = reserv.getJSONObject(一);
联系人[A] = c.getString(TAG_FULLNAME);
}
} 其他 {
的System.out.println(找不到用户);
}
}赶上(JSONException E){
的System.out.println(E3+ e.toString());
}
返回null;
}
保护无效onPostExecute(字符串file_url){
// ArrayList中有重复的字符串
名单<字符串> dupList =(名单<字符串>)Arrays.asList(联系人);
//转换的ArrayList到HashSet的删除重复
LinkedHashSet<字符串> listToSet =新LinkedHashSet<字符串>(dupList);
//创建ArrayList的不重复的值
名单<字符串> contlist =新的ArrayList<字符串>(listToSet);
的System.out.println(客户名单+ contlist);
ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串>(Custname.this,android.R.layout.simple_dropdown_item_1line,contlist);
//设置适配器
txtcustname.setAdapter(适配器);
txtcustname.setThreshold(1);
}
}
类ReserveInfo扩展的AsyncTask<字符串,字符串,字符串> {
@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(Custname.this);
pDialog.setMessage(加载预约);
pDialog.setIndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
}
保护字符串doInBackground(字符串参数... args){
字符串N = txtcustname.getText()的toString();
名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
params.add(新BasicNameValuePair(TAG_FULLNAME,N));
json2 = jParser2.makeHtt prequest(http://10.0.2.2/Laicamproject/cName.php,POST,则params);
的System.out.println(PARAMS+参数);
尝试 {
reserv2 = json2.getJSONArray(TAG_RESERV);
的System.out.println(保留+ reserv2.toString());
INT I = 0;
}赶上(JSONException E){
// TODO自动生成的catch块
的System.out.println(E1 ==+ e.toString());
}
返回null;
}
保护无效onPostExecute(字符串file_url){
pDialog.dismiss();
INT NUM = 1;
的JSONObject C2;
尝试 {
INT成功= json2.getInt(TAG_SUCCESS);
如果(成功== 1){
的for(int i = 0; I< reserv2.length();我++){
C2 = reserv2.getJSONObject(ⅰ);
//System.out.println("c2.getString(TAG_CONTACT).==="+c2.getString(TAG_CONTACT));
//System.out.println("c2.getString(TAG_FULLNAME).==="+c2.getString(TAG_FULLNAME));
custinfo2.setText(名称\ T:+ c2.getString(TAG_FULLNAME)
+\ nPhone \ t+ c2.getString(TAG_CONTACT));
lblempty2.append(\ N [+数字+]+日期\ t \ t+ c2.getString(TAG_DATE)
+\ñ\ t时间\ t \ t+ c2.getString(TAG_TIME)
+\ñ\ t大同\ t \ t \ t+ c2.getString(TAG_PAX)
+\ñ\ T台上的\ t \ t+ c2.getString(TAG_TABLE)+\ N);
}
}其他{
showAlert();
}
}赶上(JSONException E){
// TODO自动生成的catch块
的System.out.println(E2 ==+ e.toString());
}
}
公共无效的onClick(视图v){
// TODO自动生成方法存根
}
}
@覆盖
公共无效的onClick(视图v){
// TODO自动生成方法存根
}
公共无效showAlert(){
Custname.this.runOnUiThread(新的Runnable(){
公共无效的run(){
AlertDialog.Builder建设者=新AlertDialog.Builder(Custname.this);
builder.setTitle(没有联系电话找到)
.setCancelable(假)
.setPositiveButton(OK,新DialogInterface.OnClickListener(){
公共无效的onClick(DialogInterface对话框,INT ID){
txtcustname.setText();
复位();
}
});
AlertDialog警报= builder.create();
alert.show();
}
});
}
公共无效复位(){
lblempty2.setText();
custinfo2.setText();
}
}
我接过来一看你的PHP和,对我来说,似乎是根是一个 JSONArray
和不是的JSONObject
。你的 makeHtt prequest
应该返回的 JSONArray
代替的JSONObject
此外,在Java的字符串比较是通过等于
的方法进行,==检查字符串
的参考。
例如
如果(方法==POST)
和的if-else
分公司也
I'm having problem with string cannot convert to JSONObject.Anyone could help to solve this problem? Thanks and very appreciate for helping.
<?php
mysql_connect("localhost","test","");
mysql_select_db("test");
$response = array();
$fullname=$_POST["fullname"];
$result = mysql_query("select fullname,contact, DATE_FORMAT(reserveDate,'%e-%c-%Y') reserveDate,
DATE_FORMAT(reserveTime,'%h:%i %p') reserveTime,
pax,tableNumber
from reserve inner join customer using (customerID)
where fullname=$fullname" );
if (mysql_num_rows($result) > 0) {
$response["reserve"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$reserv = array();
$reserv["fullname"] = $row["fullname"];
$reserv["contact"] = $row["contact"];
$reserv["reserveDate"] = $row["reserveDate"];
$reserv["reserveTime"] = $row["reserveTime"];
$reserv["pax"] = $row["pax"];
$reserv["tableNumber"] = $row["tableNumber"];
// push single product into final response array
array_push($response["reserv"], $reserv);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
?>
JSONPARSER class
package com.example.easy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
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 method
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));
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"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
//json = sb.toString();
json = sb.toString().substring(0, sb.toString().length()-1);
System.out.println("jsonstring ="+json);
is.close();
} 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;
}
}
There is an error occur in ReserveInfo class. Get this error" value .
package com.example.easy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
public class Custname extends Activity implements OnClickListener {
TextView custinfo2,lblempty2;
Button btnsearch1;
TextView custinfo,lblempty;
ScrollView svcustdetails, svreserve;
AutoCompleteTextView txtcustname ;
String Contacts[];
int arraysize;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
JSONParser jParser2 = new JSONParser();
private static final String TAG_SUCCESS = "success";
private static final String TAG_RESERV = "reserv";
private static final String TAG_FULLNAME = "fullname";
private static final String TAG_CONTACT = "contact";
private static final String TAG_DATE = "reserveDate";
private static final String TAG_TIME = "reserveTime";
private static final String TAG_PAX = "pax";
private static final String TAG_TABLE = "tableNumber";
JSONArray reserv = null;
JSONArray reserv2 = null;
JSONObject json2;
String contactno;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custname);
btnsearch1= (Button) findViewById(R.id.btnsearch);
svcustdetails=(ScrollView)findViewById(R.id.svcustdetails);
svreserve=(ScrollView)findViewById(R.id.svreserve);
custinfo2=(TextView)findViewById(R.id.custinfo2);
txtcustname = (AutoCompleteTextView)findViewById(R.id.txtcustname);
txtcustname = (AutoCompleteTextView)findViewById(R.id.txtcustname);
btnsearch1= (Button) findViewById(R.id.btnsearch1);
lblempty2= (TextView)findViewById(R.id.lblempty2);
new LoadContact().execute();
btnsearch1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
if(txtcustname.getText().toString().equalsIgnoreCase("")){
Toast.makeText(Custname.this,"Please enter customer name", Toast.LENGTH_SHORT).show();
}else{
reset();
new ReserveInfo().execute();
}
}
});
}
class LoadContact extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest("http://10.0.2.2/Laicamproject/checkName.php", "GET", params);
// Check log cat for JSON reponse
Log.d("All Name: ", json.toString());
Contacts=new String[arraysize];
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
reserv = json.getJSONArray(TAG_RESERV);
arraysize=reserv.length();
Contacts=new String[arraysize];
for(int a=0;a<arraysize;a++){
JSONObject c = reserv.getJSONObject(a);
Contacts[a]=c.getString(TAG_FULLNAME);
}
} else {
System.out.println("no user found");
}
} catch (JSONException e) {
System.out.println("e3"+e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
//ArrayList with duplicates String
List<String> dupList = (List<String>) Arrays.asList(Contacts);
//Converting ArrayList to HashSet to remove duplicates
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(dupList);
//Creating Arraylist without duplicate values
List<String> contlist = new ArrayList<String>(listToSet);
System.out.println("Customer list: " + contlist );
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Custname.this,android.R.layout.simple_dropdown_item_1line,contlist );
// Set the adapter
txtcustname.setAdapter(adapter);
txtcustname.setThreshold(1);
}
}
class ReserveInfo extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Custname.this);
pDialog.setMessage("Loading reservation");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String n=txtcustname.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_FULLNAME,n ));
json2 = jParser2.makeHttpRequest("http://10.0.2.2/Laicamproject/cName.php","POST", params);
System.out.println("params"+params);
try {
reserv2 = json2.getJSONArray(TAG_RESERV);
System.out.println("Reservation"+reserv2.toString());
int i=0;
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("e1=="+e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
int num=1;
JSONObject c2;
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
for(int i=0;i<reserv2.length();i++){
c2 = reserv2.getJSONObject(i);
//System.out.println("c2.getString(TAG_CONTACT).==="+c2.getString(TAG_CONTACT));
//System.out.println("c2.getString(TAG_FULLNAME).==="+c2.getString(TAG_FULLNAME));
custinfo2.setText("Name \t: "+ c2.getString(TAG_FULLNAME)
+"\nPhone \t: " + c2.getString(TAG_CONTACT));
lblempty2.append("\n["+num+"] "+"Date \t\t: "+ c2.getString(TAG_DATE)
+"\n\t Time \t\t: " + c2.getString(TAG_TIME)
+"\n\t Pax \t\t\t: "+ c2.getString(TAG_PAX)
+"\n\t Table \t\t: "+ c2.getString(TAG_TABLE)+"\n");
}
}else{
showAlert();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
System.out.println("e2=="+e.toString());
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
public void showAlert(){
Custname.this.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(Custname.this);
builder.setTitle("No contact number found")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
txtcustname.setText("");
reset();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
public void reset(){
lblempty2.setText("");
custinfo2.setText("");
}
}
I took a look to your php and, to me, seems that the root is a JSONArray
and not a JSONObject
. Your makeHttpRequest
should return a JSONArray
instead of a JSONObject
Also String comparison in Java is performed through the equals
method, == check the String
's reference.
For instance
if(method == "POST")
and if-else
branch also
这篇关于的值小于错误; java.lang.String类型BR无法转换成的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!