gson的安装和使用
2024-08-28 06:49:48
gson的安装和使用
1.安装
2.布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/response_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
3.查看声明
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "demo.jq.com.networktest"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.google.code.gson:gson:2.8.2'
}
4.创建接收数据的类
package demo.jq.com.networktest;
import java.lang.reflect.Array;
/**
* @author jim
*/
public class ApiData {
String[] data =new String[5];
private Integer code;
private String message;
public String[] getData() {
return data;
}
public void setData(String[] data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
5.主体动作
package demo.jq.com.networktest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
* @author jim
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView responseText;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithOkHttp();
}
}
private void sendRequestWithOkHttp() {
// 开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
OkHttpClient client = new OkHttpClient();
// post请求
RequestBody requestBody = new FormBody.Builder()
.add("type","1")
.build();
Request request = new Request.Builder()
.url("http://devmg.yunlutong.com/api/test/testApi")
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
// 解析json数据
parseJSONWithGSON(responseData);
showResponse(responseData);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
/**
* 解析json
* @param jsonData
*/
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
ApiData apiData = gson.fromJson(jsonData, ApiData.class);
Log.d(TAG,"code is" + apiData.getCode());
Log.d(TAG,"message is" + apiData.getMessage());
// 遍历数据
for(int i = 0; i < apiData.getData().length; i++){
Log.d(TAG,"data "+i+" is " + apiData.getData()[i]);
}
}
private void showResponse(final String response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
responseText.setText(response);
}
});
}
}
最新文章
- UITableview中怎么找到每个cell
- (二)SQL Server分区创建过程
- JSON+YAML初步学习+ciscoconfparse
- PHP debug 环境配置
- 【hiho一下第77周】递归-减而治之 (MS面试题:Koch Snowflake)
- CSS颜色代码大全
- SQL Server 阻止了对组件 &#39;Ole Automation Procedures&#39; 的 过程&#39;sys.sp_OACreate&#39; 的访问
- Nagios页面介绍(四)
- 【英语】Bingo口语笔记(72) - play系列
- BestCoder Round #68 (div.2) geometry(hdu 5605)
- ★ Linked List Cycle II -- LeetCode
- HTML5 FileReader读取Blob对象API详解
- POJ 2513 Colored Sticks - from lanshui_Yang
- python机器学习实战(二)
- Chapter 5 Blood Type——9
- HDU 1098(条件满足 数学)
- Loadrunner通过吞吐量计算每个用户需要的带宽
- sqlserver 获取数据库、表和字段相关信息
- L2 Helios OPcodez
- 【LeetCode】Validate Binary Search Tree 二叉查找树的推断
热门文章
- uiautomator中InteractionController学习笔记(8)
- 【剑指Offer学习】【面试题26:复杂链表的复制】
- 2015.05.11,外语,读书笔记-《Word Power Made Easy》 15 “如何谈论事情进展” SESSION 44
- oracle 索引优化之distinct
- sql获得某个时间段的数据
- Array.prototype.slice.call(arguments) 通俗法理解
- html5中canvas(2)
- NSRunloop总结
- 【AnjularJS系列6 】 过滤器
- Mac Technology Overview