一、常用的Json解析类
1、JSONObject
Json对象
有两个不同的取值方法:
- get×××(String name)
在确定数值存在的条件下使用,否则当无法检索到相关Key时,将会抛出一个Exception信息。 - opt×××(String name)
这个方法相对比较灵活,当无法获取所指定数值时,将会返回一个默认数值,并不会抛出异常。
2、JSONArray
Json数组
二、案例
1、源码
下载Json资源
public class MyAsync extends AsyncTask<String, Void, String> {
private Handler handler;
public MyAsync(Handler handler) {
this.handler = handler;
}
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//拿到输入流
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder result = new StringBuilder();
char[] buffer = new char[512];
int bufsize;
while ((bufsize = reader.read(buffer)) > 0) {
result.append(buffer, 0, bufsize);
}
return result.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Message message = Message.obtain();
message.obj = s;
handler.sendMessage(message);
}
}
public class MainActivity extends AppCompatActivity {
String url = "https://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&page=1&limit=5";
String result = null;
private TextView resultTextView;
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
result = (String) msg.obj;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyAsync myAsync = new MyAsync(handler);
myAsync.execute(url);
resultTextView = findViewById(R.id.result_text);
}
}
下载成功的json数据使用JSON数据格式化验证结果如下
{
"ret":1,
"data":[
{
"id":"8289",
"title":"油焖大虾",
"pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg",
"collect_num":"1670",
"food_str":"大虾 葱 生姜 植物油 料酒",
"num":1670
},
{
"id":"2127",
"title":"四川回锅肉",
"pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg",
"collect_num":"1591",
"food_str":"猪肉 青蒜 青椒 红椒 姜片",
"num":1591
},
{
"id":"30630",
"title":"超简单芒果布丁",
"pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg",
"collect_num":"1549",
"food_str":"QQ糖 牛奶 芒果",
"num":1549
},
{
"id":"9073",
"title":"家常红烧鱼",
"pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/10/9073.jpg",
"collect_num":"1426",
"food_str":"鲜鱼 姜 葱 蒜 花椒",
"num":1426
},
{
"id":"10097",
"title":"家常煎豆腐",
"pic":"http://www.qubaobei.com/ios/cf/uploadfile/132/11/10097.jpg",
"collect_num":"1419",
"food_str":"豆腐 新鲜红椒 青椒 葱花 油",
"num":1419
}
]
}
解析
private String parseJson(String json) {
StringBuffer sb = new StringBuffer();
try {
JSONObject object = new JSONObject(json);
String retString = object.getString("ret");
Log.d("jsonTest", "ret = " + retString + "\n");
JSONArray dataJSONArray = object.getJSONArray("data");
for(int i = 0; i < dataJSONArray.length(); i++) {
JSONObject jsonObject = dataJSONArray.getJSONObject(i);
String idString = jsonObject.getString("id");
String titleString = jsonObject.getString("title");
String picString = jsonObject.getString("pic");
String collect_numString = jsonObject.getString("collect_num");
String food_strString = jsonObject.getString("food_str");
int numInt = jsonObject.getInt("num");
String message = "id = " + idString
+ " , title = " + titleString
+ " , pic = " + picString
+ " , collect_num = " + collect_numString
+ " , food_str = " + food_strString
+ " , num = " + numInt
+ "\n\n";
Log.d("jsonTest", message);
sb.append(message);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
显示
private Handler handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
result = (String) msg.obj;
resultTextView.setText(parseJson(result));
}
};