首先导入Google的包:
compile 'com.google.code.gson:gson:2.7'
然后我们需要创建一个类来作为解析的Json数据类型(Json文件格式见26):
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
然后实现Gson方式解析Json数据:
public class JsonGetWithGsonActivity extends Activity {
private Button send_http;
private TextView get_http;
private String responseData;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ok_http);
send_http = findViewById(R.id.send_Okhttp);
get_http = findViewById(R.id.get_Okhttp);
send_http.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendRequestWithOkHttp();
}
});
get_http.setMovementMethod(new ScrollingMovementMethod());
}
private void sendRequestWithOkHttp() {
//请求网络操作必须要在子线程中进行(主线程会报错)
new Thread(new Runnable() {
@Override
public void run() {
try {
//创建一个OkHttpClient实例
OkHttpClient client = new OkHttpClient();
//如果要发起一条HTTP请求,就需要创建一个Request对象
//GET请求
Request request = new Request.Builder()
.url("http://192.168.1.249/new.json")
.build();
//POST请求(需要一个RequestBody来存放需要提交的参数)
// RequestBody requestBody = new FormBody.Builder()
// .add("arg1","123")
// .add("arg2","123456")
// .build();
// Request request = new Request.Builder()
// .url("http://www.baidu.com")
// .post(requestBody)
// .build();
//调用newCall()方法来创建一个Call对象,并调用他的execute()方法来发送请求并获取服务器返回的数据
Response response = client.newCall(request).execute();
//得到返回的服务器的数据内容
responseData = response.body().string();
//-----------------------------------------------
//这里开始处理接收到的json文件
parseJSONWithGSON(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
//这里使用TypeToken将期望解析成的数据类型传入到fromJson()方法中
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>(){}.getType());
for(App app : appList){
Log.v("JsonGetWithGsonActivity", "id is:" + app.getId());
Log.v("JsonGetWithGsonActivity", "name is:" + app.getName());
Log.v("JsonGetWithGsonActivity", "version is:" + app.getVersion());
}
}
}