[英]Convert JSONObject to JSONArray
我正在使用此JSONParser.java:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} 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;
}
}
可以满足我的其他要求。 现在我的php文件发送一个数组。 如何将其转换为Jarray或直接在ArrayList中转换,可以在我的应用程序中使用?
数组(2个项目)如下所示:
03-15 20:40:16.667: E/JSON(26100): [{"ean":"8029694000","name":"KRINGS-VERBAU","betriebsdatenalt":"412"},{"ean":"8026786937","name":"KOMPRESSOR FAHR 5,3 M3 XAS97DDG","betriebsdatenalt":"0"}]
如果你有一个数组
JSONArray myArray=new JSONArray(string)
现在遍历数组并得到像
ArrayList<JSONObject> yourObjects=new ArrayList<JSONObject>();
for(int i=0;i<myArray.length();i++){
yourObjects.add(myArray.getJSONObject(i))
}
还要每次检查它是否是一个对象或数组
JSONObject obj=new JSONObject(string from server);
if(obj==null){
JSONArray array=new JSONArray(string from server)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.