Gson解析Json数据的通用方法

1 环境配置

引入Gson的依赖包即可。


2 原始数据

String gs = "{" + "country:{" + "city:{" + "persons:[" + "{name:gaofeng,age:22},"+ "{name:bing,age:23}" + "]" + "}" + "}" + "}";

3 开始解析

1 编写各层Bean类

1 person层

class Person {
  private String name;
  private int age;
  //get、set省略
 ...
}

2 city层

class City {
  //因为原始数据中的person层为多个对象,故需要使用集合
  private List persons;
  //get、set省略
 ...
}

3 country层

class Country {
  private City city;
  //get、set省略
  ...
}
4 新增最外层
class T {
  private Country country;
 //get、set省略
 ...
}

2 用Gson解析

Gson gson = new Gson();
T t = gson.fromJson(gs, T.class);
Listpp=t.getCountry().getCity().getPs();
for (Person person : pp) {
  System.out.println(">>>"+person);
}

3 注意点

那么问题来了:

你们在自己尝试的时候有没有报空指针的问题呢?

上面看似简单,其实里面有个需要注意的地方地方,那就是各层变量名需要与原始数据中各层的节点一致!

你可能感兴趣的:(开源框架)