我们一般从第三方数据提供方(接口提供者)获取到的数据格式都是json格式,而最常见的是二维关联性数组,如:
//php写法,
$man=array("id"=>9,"name"=>"张三丰",“age”=>"99");
或者:
$man["id"]=9;
$man["name"]="张三丰";
$man["age"]=99;
//这些数据也可以来自数据库,更可以是多条如:
$man=array("1"=>array("id"=>9,name"=>"张三丰",“age”=>"99"),
"2"=>array("id"=>3,name"=>"张四丰",“age”=>"88"),
"5"=>array("id"=>4,name"=>"张九丰",“age”=>"77"),
);
//上面这种最最常见,用Gson解析的方法,如:
package guide.test.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class TestGsonActivity extends AppCompatActivity {
String jsonSring="[{\"img\":\"123.jpg\",\"title\":\"aaaaaa\"},{\"img\":\"456.jpg\",\"title\":\"bbbbbb\"}]";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_gson);
Gson gson=new Gson();
Type type = new TypeToken<ArrayList<JsonDate>>() {}.getType();
List<JsonDate> result=gson.fromJson(jsonSring,type);
for(JsonDate i:result) {
Log.e("ttt", i.img+"和"+i.title);
}
}
class JsonDate{
private String img;
private String title;
public void setImg(String img){
this.img=img;
}
public String getImg(){
return img;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return title;
}
}
}
注意:
1,复杂结构的json内部类的结构编写是关键,
2,本例没有直接读取接口,只是模拟了接口数据,
3,Type type = new TypeToken<ArrayList<JsonDate>>() {}.getType();
Type是java里的reflect包的Type ,TypeToken 是google提供的一个解析Json数据的类库中一个类