1. 解析单个JSON对象
try
{
String JString="{\"Name\":\"George\",\"Age\":30,\"Birthday\":\"1982-3-17\"}";
JSONObject jsonObject = new JSONObject(JString);
String uid = jsonObject.getString("Name");
int a = jsonObject.getInt("Age");
String bir = jsonObject.getString("Birthday");
new AlertDialog.Builder(this).setTitle("Hint").setMessage(uid).setPositiveButton("OK", null).show();
new AlertDialog.Builder(this).setTitle("Hint").setMessage(String.valueOf(a)).setPositiveButton("OK", null).show();
new AlertDialog.Builder(this).setTitle("Hint").setMessage(bir).setPositiveButton("OK", null).show();
}
catch(Exception e)
{
e.printStackTrace();
}
2. 解析JSON数组
try
{
String JString="[{ \"id\": \"HAHA\", \"version\": \"abc\" },{ \"id\": \"BABA\", \"version\": \"bbc\" },{ \"id\": \"CACA\", \"version\": \"Wa_\" }]";
//JSONObject jsonObject = new JSONObject(JString);
JSONArray ja = new JSONArray(JString);
for(int i=0;i<ja.length();i++)
{
JSONObject jsonObject2 = (JSONObject)ja.get(i);
String uid = jsonObject2.getString("id");
new AlertDialog.Builder(this).setTitle("Hint").setMessage(uid).setPositiveButton("OK", null).show();
}
}
catch(Exception e)
{
e.printStackTrace();
}
本文介绍了如何使用Java解析JSON格式的数据,包括单个JSON对象和JSON数组。通过具体示例展示了如何提取JSON对象中的字符串、整数等类型的数据,以及遍历JSON数组并获取每个元素的指定字段。

被折叠的 条评论
为什么被折叠?



