JSON数据的解析
在解析JSON数据时,往往遇到的JSON格式并没有书上列举的那么简单, 在此我举例几种JSON格式:这下面JSON数据来自于一篇别人的博客
- {
“name”:“李四”,
“age”:99,
“hobby”:“爱好是练习截拳道”
}
用这一对花括号括起来的是一个JSON对象
private void parseJSONWithJSONObject(String jsonData){
try{
JSONObject objectAll = new JSONObject(jsonData);
String data = objectAll.optString("name",null);
int age = objectAll.optInt("age",0);
String hobby = objectAll.optString("hobby",null);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
- {
“student”:{
“name”:“李四”,
“age”:99,
“hobby”:“爱好是练习截拳道”
}
}
private void parseJSONWithJSONObject(String jsonData){
try{
JSONObject objectAll = new JSONObject(jsonData);
String student = objectAll.optString("student",null);
//我们经常使用TextUtils.isEmpty()来判断字符串是否为null或者空字符串,防止出现空指针异常
if(!TextUtils.isEmpty(student)){
JSONObject object = new JSONObject(student);
String data = object.optString("name",null);
int age = object.optInt("age",0);
String hobby = object.optString("hobby",null);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
{
“student”:{
“name”:“李四”,
“age”:99,
“hobby”:“爱好是练习截拳道”,
“dog”:{
“name”:“阿黄”,
“age”:77,
“sex”:“母”
}
}
}
JSON数据的嵌套
private void parseJSONWithJSONObject(String jsonData){
try{
JSONObject objectAll = new JSONObject(jsonData);
String student = objectAll.optString("student",null);
//我们经常使用TextUtils.isEmpty()来判断字符串是否为null或者空字符串,防止出现空指针异常
if(!TextUtils.isEmpty(student)){
JSONObject object = new JSONObject(student);
String dog = object.optString("dog",null);
String data = object.optString("name",null);
int age = object.optInt("age",0);
String hobby = object.optString("hobby",null);
if(!TextUtils.isEmpty(dog)){
JSONObject objectDog = new JSONObject(dog);
String data =objectDo.optString("name",null);
int age = objectDo.optInt("age",0);
String hobby = objectDo.optString("sex",null);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
- [
{
“name”:“君君”,
“age”:89,
“sex”:“男”
},
{
“name”:“小君”,
“age”:99,
“sex”:“女”
},
{
“name”:“大君”,
“age”:88,
“sex”:“男”
}
]
用[]括起来的是JSONArray数组。
private void parseJSONWithJSONObject(String jsonData){
try{
JSONObject objectAll = new JSONObject(jsonData);
JSONArray array = new JSONArray(jsonData);
for(int i = 0; i < array.length(); i ++){
JSONObject trueObject = array.getJSONObject(i);
String data = trueObject.optString("name",null);
int age = trueObject.optInt("age",0);
String sex = trueObject.optString("sex",null);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}
{
“person”:[
{
“name”:“君君”,
“age”:89,
“sex”:“男”
},
{
“name”:“小君”,
“age”:99,
“sex”:“女”
},
{
“name”:“大君”,
“age”:88,
“sex”:“男”
}
]
}
private void parseJSONWithJSONObject(String jsonData){
try{
JSONObject objectAll = new JSONObject(jsonData);
JSONArray array = objectAll.getJSONArray("person")
for(int i = 0; i < array.length(); i ++){
JSONObject trueObject = array.getJSONObject(i);
String data = trueObject.optString("name",null);
int age = trueObject.optInt("age",0);
String sex = trueObject.optString("sex",null);
}
}
}catch (Exception e){
e.printStackTrace();
}
}
}