解析JSON格式数据
解析JSON格式数据
1、使用JSONObject
1、首先接收服务器返回的数据
private void okHttpRequest() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//指定访问的服务器地址是电脑本机
.url("http://10.0.2.2/get_data.json")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWITHJSONObject(responseData);//解析数据
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
2、解析JSON格式数据
private void parseJSONWITHJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonobject = jsonArray.getJSONObject(i);
String id = jsonobject.getString("id");
String name = jsonobject.getString("name");
String version = jsonobject.getString("version");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
2、使用GSON解析
1.首先添加依赖
implementation 'com.google.code.gson:gson:2.7'
GSON库主要就是可以将一段JSON格式的字符串自动映射成一个对象,从而不需要我们在手动去编写代码进行解析。
比如说一段JSON格式数据如下:
String jsonData = {"name":"Tom","age":20};
那我们就可以定义一个Person类,并加入name和age字段,然后只需要调用如下代码就可以JSON数据自动解析成Person对象:
Gson gson = new Gson();
Person person = gson.fromJson(jsonData, Person.class);
如果需要解析的是一段JSON数组会稍微麻烦一点,我们需要借助TypeToken将期望解析的数据类型传入到fromJson()方法中:
Gson gson = new Gson();
List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>().getType());
2、定义Person类
public class Person {
private String id;
private String name;
private int age;
/*
getter and setter
*/
}
3.接收服务器返回的数据
private void okHttpRequest() {
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//指定访问的服务器地址是电脑本机
.url("http://10.0.2.2/get_data.json")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWithGSON(responseData);//解析数据
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
4.解析JSON数据
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<Person> people = gson.fromJson(jsonData, new TypeToken<List<Person>>(){}.getType());
for (Person person : people) {
String id = person.getId();
String name = person.getName();
int age = person.getAge();
}
}
3、使用实例
1、定义原始的JSON数据如下(test.json)
[
{
"name":"why",
"age":"26",
"sex":"male"
},
{
"name":"jr",
"age":"24",
"sex":"female"
}
]
2、MainActivity.java
package com.hfut.operationjson;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
EditText jsonName;
TextView jsonContent;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
jsonContent.setText((String) msg.obj);
break;
}
}
};
public final String localURL = "http://192.168.31.2:8088/";
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
jsonName = findViewById(R.id.json_name);
jsonContent = findViewById(R.id.json_content);
}
public void jSONObjectParse(View view) {
getData(view.getId());
}
public void gSONParse(View view) {
getData(view.getId());
}
//JSONObject对象解析
private String parseJSONwithJSONObject(String jsonData) {
StringBuilder stringBuilder = new StringBuilder();
try {
JSONArray array = new JSONArray(jsonData);
Log.i(TAG, "parseJSONwithJSONObject: "+array.length());
//遍历json串,获取每一个json对象,在取键值对数据
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
String name = jsonObject.getString("name");
String age = jsonObject.getString("age");
String sex = jsonObject.getString("sex");
stringBuilder.append(" name:"+name+"; age:"+age+"; sex:"+sex+"\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}
//GSON解析
private String parseJSONwithGSON(String jsonData) {
Gson gson=new Gson();
StringBuilder stringBuilder = new StringBuilder();
//通过json字符串获取对象数组
List<Student> list=gson.fromJson(jsonData,new TypeToken<List<Student>>(){}.getType());
for (int i = 0; i < list.size(); i++) {
Student student=list.get(i);
String name = student.getName();
String age =student.getAge();
String sex = student.getSex();
stringBuilder.append(" name:"+name+"; age:"+age+"; sex:"+sex+"\n");
}
return stringBuilder.toString();
}
private void getData(final int methodID){
final StringBuilder stringBuilder = new StringBuilder();
new Thread(new Runnable() {
@Override
public void run() {
String tempUrl = localURL + jsonName.getText().toString();
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(tempUrl)
.build();
try {
Response response = okHttpClient.newCall(request).execute();
String result = response.body().string();
Message message = new Message();
String parsedData="";
//点击不同按钮,执行不同的解析方法
switch (methodID){
case R.id.JSONObjectWay:
parsedData=parseJSONwithJSONObject(result);
stringBuilder.append("解析方式为:JSONObjectWay\n");
break;
case R.id.GSONWay:
parsedData=parseJSONwithGSON(result);
stringBuilder.append("解析方式为:GSONWay\n");
break;
}
stringBuilder.append("源数据为:\n");
stringBuilder.append(result+"\n");
stringBuilder.append("解析数据结果:\n");
stringBuilder.append(parsedData);
message.what = 1;
message.obj = stringBuilder.toString();
handler.sendMessage(message);
Log.i(TAG, "run: " + result);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
3、Student.java
package com.hfut.operationjson;
public class Student {
private String name;
private String age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
4、activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.hfut.operationjson.MainActivity">
<EditText
android:layout_marginTop="20dp"
android:id="@+id/json_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入JSON文件名称"
android:textSize="20dp" />
<Button
android:id="@+id/JSONObjectWay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textAllCaps="false"
android:onClick="jSONObjectParse"
android:text="JSONObject解析JSON"
android:textSize="20dp" />
<Button
android:id="@+id/GSONWay"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="gSONParse"
android:text="GSON解析JSON"
android:textSize="20dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp">
<TextView
android:textSize="20dp"
android:textColor="@color/colorPrimary"
android:id="@+id/json_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="显示服务器JSON文件数据" />
</ScrollView>
</LinearLayout>
实验结果
1、第一步:运行程序
第二步:点击“JSONObject解析JSON”
第三步:点击“GSON解析JSON”
参考
1、Android-解析JSON格式数据
2、https://blog.csdn.net/hfut_why/article/details/79919015
3、深入分析JSON多种解析方式(Gson、AS自带org.json、Jackson)