本文介绍了java.lang.String中不能转换到的JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图从数据库中检索数据时面临的问题:
错误解析数据org.json.JSONException:值< java.lang.String类型的DOCTYPE不能转换为JSONObject的!公共类AllProductsActivity扩展ListActivity { //进度对话框
私人ProgressDialog pDialog; //创建JSON解析器对象
JSONParser jParser =新JSONParser(); ArrayList的<&HashMap的LT;字符串,字符串>>产品列表; // URL获得所有产品清单
私人静态字符串url_all_products =http://192.168.1.3/android_connect/get_all_products.php; // JSON节点名称
私有静态最后弦乐TAG_SUCCESS =成功;
私有静态最后弦乐TAG_PRODUCTS =产品;
私有静态最后弦乐TAG_PID =PID;
私有静态最后弦乐TAG_NAME =名; //产品JSONArray
JSONArray产品= NULL; @覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.all_products); //为哈希映射的ListView
产品列表=新的ArrayList<&HashMap的LT;字符串,字符串>>(); //装载产品在后台线程
新LoadAllProducts()执行(); //获取列表视图
ListView控件LV = getListView(); //在选课单品
//启动编辑产品屏幕
lv.setOnItemClickListener(新OnItemClickListener(){ @覆盖
公共无效onItemClick(适配器视图<>母公司,观景,
INT位置,长的id){
//从选定的ListItem得到的值
字符串的pid =((的TextView)view.findViewById(R.id.pid))的getText()。
的ToString(); //开始新意图
在意向=新意图(getApplicationContext()
EditProductActivity.class);
//发送到PID下一个活动
in.putExtra(TAG_PID,PID); //开始新的活动,期待一些回响应
startActivityForResult(在100);
}
}); } //从编辑产品的活动响应
@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
super.onActivityResult(要求code,结果code,数据);
//如果结果code 100
如果(结果code == 100){
//如果结果code 100接收
//意味着用户编辑/删除产品
//重新载入该画面
意向意图= getIntent();
完();
startActivity(意向);
} } / **
*背景异步任务以通过HTTP请求负载的所有产品
* * /
类LoadAllProducts扩展的AsyncTask<字符串,字符串,字符串> { / **
*启动后台线程显示进度对话框之前
* * /
@覆盖
在preExecute保护无效(){
super.on preExecute();
pDialog =新ProgressDialog(AllProductsActivity.this);
pDialog.setMessage(加载产品请稍候......);
pDialog.setIndeterminate(假);
pDialog.setCancelable(假);
pDialog.show();
} / **
*让所有的产品网址
* * /
保护字符串doInBackground(字符串参数... args){
//大厦参数
清单<&的NameValuePair GT; PARAMS =新的ArrayList<&的NameValuePair GT;(); // URL从获取JSON字符串
JSONObject的JSON = jParser.makeHtt prequest(url_all_products,GET,则params); //检查JSON效应初探日志的猫
Log.d(所有产品,json.toString()); 尝试{
//检查成功TAG
INT成功= json.getInt(TAG_SUCCESS); 如果(成功== 1){
发现//产品
//获取产品阵列
产品= json.getJSONArray(TAG_PRODUCTS); //产品通过所有循环
的for(int i = 0; I< products.length();我++){
JSONObject的C = products.getJSONObject(I) //存储在变量中的每个JSON项目
字符串ID = c.getString(TAG_PID);
字符串名称= c.getString(TAG_NAME); //创建新的HashMap
HashMap的<字符串,字符串>地图=新的HashMap<字符串,字符串>(); //将每个子节点的HashMap键=>值
map.put(TAG_PID,身份证);
map.put(TAG_NAME,名); //添加HashList到ArrayList的
productsList.add(地图);
}
}其他{
//没有发现产品
//启动添加新产品活动
意图I =新意图(getApplicationContext()
NewProductActivity.class);
//关闭所有previous活动
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ⅰ);
}
}赶上(JSONException E){
e.printStackTrace();
} 返回null;
} / **
*在完成后台任务之后辞退进度对话框
* ** /
保护无效onPostExecute(字符串FILE_URL){
//让所有的产品后,关闭该对话框
pDialog.dismiss();
//从后台线程更新界面
runOnUiThread(新的Runnable(){
公共无效的run(){
/ **
*更新解析JSON数据到ListView控件
* * /
ListAdapter适配器=新SimpleAdapter(
AllProductsActivity.this,产品列表,
R.layout.list_item,新的String [] {TAG_PID,
TAG_NAME},
新的INT [] {R.id.pid,R.id.name});
//更新列表视图
setListAdapter(适配器);
}
}); } }
}
问题是excatly触发执行这条线时:
//获取JSON从URL字符串
JSONObject的JSON = jParser.makeHtt prequest(url_all_products,GET,则params);
这是怎么回事与code?我想,我不是编码有些不妥。
任何帮助吗?
PHP文件:
< PHP的头?('内容类型:应用程序/ JSON的;字符集= utf-8');
/ *
*继code将列出所有产品
* ///数组JSON响应
$响应=阵列();
//其中包括DB连接类
require_once __DIR__。 /db_connect.php';//连接到数据库
$ DB =新DB_CONNECT();//从产品表中的所有产品
$结果= mysql_query(SELECT * FROM产品)或死亡(mysql_error());//检查空结果
如果(mysql_num_rows($结果)大于0){
//通过所有结果循环
//产品节点
$响应[产品] =阵列(); 而($行= mysql_fetch_array($结果)){
//临时用户阵
$产品=阵列();
$产品[PID] = $行[PID];
$产品[名称] = $行[名称];
$产品[价格] = $行[价格];
$产品[说明] = $行[说明];
$产品[created_at] = $行[created_at];
$产品[的updated_at] = $行[的updated_at]; //推单一产品到最终响应数组
array_push($响应[产品],$产品);
}
//成功
$响应[成功] = 1; //呼应JSON响应
回声json_en code($响应);
}其他{
//没有发现产品
$响应[成功] = 0;
$响应[消息] =没有找到产品; //回声没有用户JSON
回声json_en code($响应);
}
?>
解决方案
相反mashalling和自己和解组的对象,检查GSON图书馆,是由谷歌开发的。
函数库的使用:
希望它帮助。
I'm facing that problem when trying to retrieving data from database:
Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://192.168.1.3/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The problem is excatly triggering when executing that line:
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
What's going on with that code? I think that i'm not coding something wrong.Any help please?
PHP FILE:
<?php header('content-type: application/json; charset=utf-8');
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
$result = mysql_query("SELECT * FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
解决方案
Instead of mashalling and unmarshalling your objects by yourself, check the Gson Library, developed by Google.
http://code.google.com/p/google-gson/
Library Usage: https://sites.google.com/site/gson/gson-user-guide
Hope it helps.
这篇关于java.lang.String中不能转换到的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!