Android 解析 JSON
要解析 JSON 數據,首先得先拿到 JSON 數據,我拿到的數據是這樣的 {"msg":"請登陸","code":-999,"data":xxx}
1、使用JSONObject來解析JSON數據
/**
* JSON解析方法
*/
protected void JSONAnalysis(String string) {
JSONObject object = null;
try {
object = new JSONObject(string);
} catch (JSONException e) {
e.printStackTrace();
}
/**
* 在你獲取的string這個JSON對象中,提取所需要的信息
*/
String msg = object.optString("msg");
String code = object.optString("code");
String data = object.optString("data");
weatherResult = "msg:" + msg + "\ncode:" + code + "\ndata:" + data;
textView.setText(weatherResult);
}
JSONObject object = new JSONObject(string); 將Json字符串解析成Json對象。
2、解析Json數組
JSONArray(String json);將json字符串解析成json數組;
private void JSONAnalysis(String JsonData) {
try{
JSONArray jsonArray = new JSONArray(jsonData);
for (int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObect.getString("version");
System.out.println("id" + id + ";name" + name + ";version" + version);
}
}catch (Exception e){
e.printStackTrace();
}
}
定義一個JSON數組,用於將服務器返回的數據傳入到一個JSONArray對象中; 然後循環遍歷這個JSONArray,從中取出每一個元素(JSONObject對象),接下來只需調用getString()方法即可將數據取出。
3、用Gson解析JSON
請參考:https://blog.csdn.net/qq_29269233/article/details/53352668
使用該方法解析JSON數據,首先需要添加GSON的jar包;
下載地址是:https://mvnrepository.com/artifact/com.google.code.gson/gson