我想在android中解析这个json数组?在android中执行它的最佳方法是什么?创建json数组到相关android json解析的最佳方法是什么。
MySql表数据(样本)
key | name | lgtime
--------------------
1 | Cat 1| 899011
2 | Cat 2| 899011
3 | Cat 3| 899011
4 | Cat 4| 899011
这个json数组是从php
创建的public static function getCategory($_lgtime) {
$con = JsonDataManip::connect();
$stmt = $con->prepare("select * from " . _TABLE_CATEGORY . " where lgtime > ?");
$stmt->execute(array($_lgtime));
while ($row = $stmt->fetch()) {
$jsonArray['key'] = $row['key'];
$jsonArray['name'] = $row['name'];
$jsonArray['lgtime'] = $row['lgtime'];
$json[] = $jsonArray;
}
return $json;
}
用法:(php)
echo json_encode(JsonDataManip::getCategory('899011'));
[{
"key":"1",
"name":"Cat 1",
"lgtime":"899011"
},
{
"key":"2",
"name":"Cat2",
"lgtime":"899011"
},
{
"key":"3",
"name":"Cat 3",
"lgtime":"899011"
}
答案 0 :(得分:1)
// try this way and let me know still have problem
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
JSONArray jsonArray = new JSONArray("jsonArrayString");
ArrayList<HashMap<String,String>> list = (ArrayList<HashMap<String,String>>)toList(jsonArray);
}catch (Exception e){
e.printStackTrace();
}
}
private Object fromJson(Object json) throws JSONException {
if (json == JSONObject.NULL) {
return null;
} else if (json instanceof JSONObject) {
return jsonToMap((JSONObject) json);
} else if (json instanceof JSONArray) {
return toList((JSONArray) json);
} else {
return json;
}
}
public Map<String, String> jsonToMap(JSONObject object) throws JSONException {
Map<String, String> map = new HashMap();
Iterator keys = object.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
map.put(key, fromJson(object.get(key)).toString());
}
return map;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private List toList(JSONArray array) throws JSONException {
List list = new ArrayList();
int size = array.length();
for (int i = 0; i < size; i++) {
list.add(fromJson(array.get(i)));
}
return list;
}
}
答案 1 :(得分:1)
试试这种方式
try {
JSONArray arrJsonArray = new JSONArray("AboveJsonString");
for (int i = 0; i < arrJsonArray.length(); i++) {
JSONObject object = arrJsonArray.getJSONObject(i);
System.out.println("Key :" + object.getString("key"));
System.out.println("name :" + object.getString("name"));
System.out.println("lgtime :" + object.getString("lgtime"));
}
} catch (Exception e) {
}
答案 2 :(得分:0)
将此字符串放在String对象
中喜欢
String jsonString = "[
{
'key': '1',
'name': 'Category 10',
'lgtime': '20140129184514896'
},
{
'key': '2',
'name': 'Category 9',
'lgtime': '20140129184514896'
},
{
'key': '3',
'name': 'Category 8',
'lgtime': '20140129184514896'
}
]"
创建JSONArray类的对象
赞:JSONArray jsonArr = new JSONArray(jsonString)
现在创建一个循环
for (int i = 0; i < jsonArr .length(); i++) {
JSONObject obj = jsonArr.getJSONObjetc(i);
// Access you element bu this object like obj.getString("key");
}