json工具
setting->plugin->gesonformat-
get 请求与 gson 用法
public class MainActivity extends AppCompatActivity {
private final String TAG = MainActivity.class.getCanonicalName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
getRequest();
}
}
).start();
}
private void getRequest(){
String url = "http://guolin.tech/api/china";
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d(TAG, "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// Log.d(TAG, "onResponse: " + response.body().string());
String responseString = response.body().string();
//因为joson数据最外面是[]所以用JSONArray来接收json字符串
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(responseString);
//获取第一个jsonobject的数据
String province1 = jsonArray.getJSONObject(0).toString();
//将json数据与实体类相关联
Gson gson = new Gson();
Province province = gson.fromJson(province1,Province.class);
Log.e(TAG, "json对象: "+province.getProvinceName());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
依赖
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
权限
<uses-permission android:name="android.permission.INTERNET"/>