从php提取json数据,并将其存储在java中的数组中 [英] json data fetched from php and store them in an array in java
本文介绍了从php提取json数据,并将其存储在java中的数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的JSON数组是这样的:
My JSON array is this:
{"Name_1":1,"Name_2":0,"Name_3":0}
和我在Java中用于获取值并将它们存储在单独的数组中的代码如下:
and my code in java for getting the values and store them in a separate array is the following:
int[] operations= new int[3];
String result = "";
InputStream is = null;
StringBuilder sb=null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://testteamgr.netau.net/parsing/test.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONObject json_data = new JSONObject(result);
System.out.println("Length of json is"+jArray.length());
for(int i=0;i<jArray.length();i++){
if (i==0) operations[0]=json_data.getInt("Name_1");
else if (i==1) operations[1]=json_data.getInt("Name_2");
else if (i==2) operations[2]=json_data.getInt("Name_3"); }
我得到那些错误:
类型为java.lang.string的value br不能转换为jsonobject
value br of type java.lang.string cannot be converted to jsonobject
如果我打印出结果,则看不到JSON对象,而是html代码.
If I print out the result I do not see the JSONobject but the html code.
所以我想要将这3个值放入一个单独的数组中.
So what I want is to get these 3 values into a separate array.
推荐答案
您有一个对象,而不是数组.要处理结果,您可以使用以下代码:
You have an object, not an array. To process the result you can use following code:
String json = "{\"Name_1\":1,\"Name_2\":0,\"Name_3\":0}";
JSONObject object = new JSONObject(json);
String[] propertyNames = JSONObject.getNames(object);
String[] values = new String[propertyNames.length];
for (int i = 0; i < propertyNames.length; i++) {
values[i] = String.valueOf(object.get(propertyNames[i]));
}
这篇关于从php提取json数据,并将其存储在java中的数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文