GsonfromJson()⽤法
1.纯数组JSON 字符串转换[ {"name": "zhangsan","age": "10","phone": "11111","email": "11111@11"}, {"name": "lisi","age": "20","phone": "22222","email": "22222@2
2"},
...]
解析代码如下:
public class UserBean {
//变量名跟JSON数据字段名必须⼀致
private String name ;
private String age;
private String phone;
private String email;
...
}
//拿到本地JSON 并转成String
String strByJson = ConstructTestJsonStr();//此处函数内容省略
//Json的解析类对象
JsonParser parser = new JsonParser();
//将JSON的String 转成⼀个JsonArray对象
JsonArray jsonArray = parser.parse(strByJson).getAsJsonArray();
Gson gson = new Gson();
ArrayList<UserBean> userBeanList = new ArrayList<>();
//加强for循环遍历JsonArray
for (JsonElement user : jsonArray) {
//使⽤GSON,直接转成Bean对象
UserBean userBean = gson.fromJson(user, UserBean.class);
userBeanList.add(userBean);
字符串转数组怎么转}
{"muser": [{"name": "zhangsan","age": "10","phone": "11111","email": "11111@11"},
{"name": "lisi","age": "20","phone": "22222","email": "22222@22"},
...]
}
//解析有数据头的纯数组
//拿到本地JSON 并转成String
String strByJson = ConstructTestJsonStr();//此处函数内容省略;
//先转JsonObject
2.有数据头的纯数组数据转换//先转JsonObject
JsonObject jsonObject = new JsonParser().parse(strByJson).getAsJsonObject();
//再转JsonArray 加上数据头
JsonArray jsonArray = AsJsonArray("muser");
Gson gson = new Gson();
ArrayList<UserBean> userBeanList = new ArrayList<>();
//循环遍历
for (JsonElement user : jsonArray) {
//通过反射得到UserBean.class
UserBean userBean = gson.fromJson(user, new TypeToken<UserBean>() {}.getType());        userBeanList.add(userBean);
}
3.有数据头的复杂数据转换{ "code": 200,"msg": "OK",
"muser": [{"name": "zhangsan","age": "10","phone": "11111","email":"11111@11"},
{"name": "lisi","age": "20","phone": "22222","email": "22222@22"},
...]
}
被解析对象不是纯数组数据,还有其它字段+数组(含头),⽅法如下:
根据 JSON 建⽴Bean,注意这⾥的 Bean 是返回所有字段,因为 GSON 能直接解析成 List ,所以 Bean 是下⾯这样的,同样把占地⽅的get/set省略:
public class ResultBean {
//注意变量名与字段名必须⼀致
private int code;
private String msg;
private List<UserBean> muser;
public class UserBean{
private String name ;
private String age;
private String phone;
private String email;
...
}
.
..
}
//有消息头复杂数据常规⽅式⽅法如下
//拿到Json字符串
String strByJson =  ConstructTestJsonStr();//此处函数内容省略;
//GSON直接解析成对象
ResultBean resultBean = new Gson().fromJson(strByJson,ResultBean.class);
//对象中拿到集合
List<ResultBean.UserBean> userBeanList = Muser();
三句话搞定,由此看出GSON的强⼤
有数据头复杂数据截取⽅式,如对第3例中JSON数据内容只想取“muser”数组中年龄(age)⼤于30岁的怎么办?
4.只解析复杂JSON 中的
数组或数组中的某部分内容⽅法1:全部解析,再从 List 中取。(但假如有1万条数据?全部解析太⿇烦),⽅法2:条件遍历!(以下代码⽰例):
//解析代码:
//拿到JSON字符串
String strByJson =  ConstructTestJsonStr();//此处函数内容省略;
List<UserBean> userBeanList = new ArrayList<>();
//拿到数组
JsonObject jsonObject = new JsonParser().parse(strByJson).getAsJsonObject();
JsonArray jsonArray = AsJsonArray("muser");
//循环遍历数组
for (JsonElement user : jsonArray) {
UserBean userBean = new Gson().fromJson(user, new TypeToken<UserBean>() {
}.getType());
//根据条件过滤
if (Integer.Age()) > 30) {
userBeanList.add(userBean);
}
}
三种⽅式:1,全部解析出来;2,要什么解析什么;3,JsonReader,第1/2招前述已解释,下⾯⽰例JsonReader(类似逐节点解释XML)
//通过JsonReader的⽅式去解析
private void parseComplexJArrayByReader() throws IOException {
String strByJson = StringByJson(this, R.raw.juser_4);
JsonReader reader = new JsonReader(new StringReader(strByJson));
try {
reader.beginObject();
String tagName = Name();
if (tagName.equals("group")) {
//读group这个节点
readGroup(reader);
}
} finally {
reader.close();
}
}
5.嵌套超复杂JSON 数据转换//读group这个节点
private void readGroup(JsonReader reader) throws IOException {    reader.beginObject();
while (reader.hasNext()) {
String tagName = Name();
if (tagName.equals("user")) {
readUser(reader);
} else if (tagName.equals("info")) {
readInfo(reader);
}
}
}
//读⽤户基本消息 user节点
private void readUser(JsonReader reader) throws IOException {    reader.beginObject();
while (reader.hasNext()) {
String tag = Name();
if (tag.equals("name")) {
String name = String();
nameText.setText(name);
} else if (tag.equals("age")) {
String age = String();
ageText.setText(age);
}
...
else {
reader.skipValue();//忽略
}
}
}
//读⽤户其他消息 info节点
private void readInfo(JsonReader reader) throws IOException {    reader.beginObject();
while (reader.hasNext()) {
while (reader.hasNext()) {        String tag = Name();        if (tag.equals("address")) {            String address = String();            addressText.setText(address);        } else if (tag.equals("work")) {            String work = String();            workText.setText(work);        }        ...        else {            reader.skipValue();//忽略        }    }    dObject();}6.简单数据+LIST+MAP 转换public class Student {                  public int id;                  public String nickName;                  public int age;                  public ArrayList<String> books;                  public HashMap<String, String> booksMap;}Student student = new Student();student.id = 1;student.nickName = "Jack";student.age = ail = "tr@qq";ArrayList<String> books = new ArrayList<String>();books.add("数学");books.add("语⽂");books.add("英语");books.add("物理");books.add("化学");books.add("⽣物");student.books = books;HashMap<String, String> booksMap = new HashMap<String, String>();booksMap.put("1", "数学");booksMap.put("2", "语⽂");booksMap.put("3", "英语");

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。