前言
本人学生一枚,现阶段也是进行Android学习,若文章中有什么错误
,请大l佬
指出。
每篇格言:
我可以一落千丈,我偏要一鸣惊人。
用GSON框架技术解析JSON
GSON框架的官网:https://mvnrepository.com/artifact/com.google.code.gson/gson
-
如果使用
Eclipse
可发选择相应版本的jar包进行下载
-
如果使用
Android Studio
开发通过Gradle,直接添加以来,不用下载jar包
Gson解析JSON对象(介绍都在代码注释中)
重要的事说一遍:
注意在使用Gson解析JSON对象时,记得创建JavaBean类,并且JavaBean类中的属性名要和JSON的key的名称相同,否则解析就会失败
JSON数据
{
"num": 1,
"age": 20,
"data": {
"chinese": 100,
"english": 90
}
}
移动端
- 结构:
重要的事说两遍:
注意在使用Gson解析JSON对象时,记得创建JavaBean类,并且JavaBean类中的属性名要和JSON的key的名称相同,否则解析就会失败
- Data
public class Data {
private int chinese;
private int english;
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
@Override
public String toString() {
return "Data{" +
"chinese=" + chinese +
", english=" + english +
'}';
}
}
重要的事说三遍:
注意在使用Gson解析JSON对象时,记得创建JavaBean类,并且JavaBean类中的属性名要和JSON的key的名称相同,否则解析就会失败
- Student
public class Student {
private int num;
private int age;
private Data data;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
@Override
public String toString() {
return "Student{" +
"num=" + num +
", age=" + age +
", data=" + data +
'}';
}
}
- NetWorkUtils
public class NetWorkUtils {
private static HttpURLConnection sHttpURLConnection;
private static BufferedReader sBufferedReader;
private static InputStream sInputStream;
/**
* 通过URL获取String
*
* @param urlStr 需要传入的URL
* @param requestWay 需要传入的请求方式(GET/POST)
* @return 返货获取的json字符串
*/
public static String sendUrlGetString(String urlStr, String requestWay) {
String jsonStr = null;
try {
// 创建URL对象
URL url = new URL(urlStr);
// 创建HttpURLConnection对象
sHttpURLConnection = (HttpURLConnection) url.openConnection();
// 设置网络的请求方式
sHttpURLConnection.setRequestMethod(requestWay);
// 设置链接主机超时
sHttpURLConnection.setConnectTimeout(8000);
// 设置从主机读取数据超时
sHttpURLConnection.setReadTimeout(8000);
// 获取输入流
sInputStream = sHttpURLConnection.getInputStream();
// 对获取到的输入流进行读取
sBufferedReader = new BufferedReader(new InputStreamReader(sInputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = sBufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
jsonStr = stringBuffer.toString();
return jsonStr;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (sBufferedReader != null) {
try {
sBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (sHttpURLConnection != null) {
sHttpURLConnection.disconnect();
}
}
return jsonStr;
}
}
- MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mJsonTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
Button gsonBtn = findViewById(R.id.gson_btn);
gsonBtn.setOnClickListener(this);
mJsonTxt = findViewById(R.id.json_txt);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.gson_btn:
new Thread(new Runnable() {
@Override
public void run() {
paraseJSONWithGSON(NetWorkUtils.sendUrlGetString("http://xxx:8080/JsonThree", "GET"));
}
}).start();
break;
}
}
private void paraseJSONWithGSON(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 创建一个Gson对象
Gson gson = new Gson();
// 调用Gson对象的fromJson(String str,Class class)
// 第一个参数 : 通过网络请求获取的JSON字符串
// 第二个参数 : 传入一个JavaBean对象
Student student = gson.fromJson(str, Student.class);
mJsonTxt.setText(student.toString());
}
});
}
}
Gson解析JSON数组(介绍都在代码注释中)
JSON数据
[
{
"id": 1,
"name": "Amy",
"age": 20
},
{
"id": 2,
"name": "Tom",
"age": 10
}
]
移动端
- People
public class People {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "People{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
- MainActivity
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mJsonTxt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
Button gsonArrayBtn = findViewById(R.id.gsonArray_btn);
gsonArrayBtn.setOnClickListener(this);
mJsonTxt = findViewById(R.id.json_txt);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.gsonArray_btn:
new Thread(new Runnable() {
@Override
public void run() {
paraseJSONWithGSONArray(NetWorkUtils.sendUrlGetString("http://XXX:8080/JsonTwo", "GET"));
}
}).start();
break;
}
}
private void paraseJSONWithGSONArray(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// 创建Gson对象
Gson gson = new Gson();
// 如果解析一段JSON数组会稍微麻烦点。我们需要借助TypeToken将期望解析成的数据类型传入到fromJson方法中。
List peopleList = gson.fromJson(s, new TypeToken>() {
}.getType());
for (People people : peopleList) {
mJsonTxt.setText("id = " + people.getId() + "\n" + "name = " + people.getName() + "\n" + "age = " + people.getAge());
}
}
});
}
}
总结
当然本篇文章中都是一些简单的JSON数据格式,适合入门学习,当然在实际开发中会很复杂的JSON数据格式,到时候大家见招拆招,不要死记解析步骤。