android:使用 Gon 解析解析 json
String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]"; 其解析
方法可以如下: try{ //如果需要解析 JSON 数据,首要要生成一个 JsonReader 对象 JsonReader reader = new JsonReader(new StringReader(jsonData)); reader.beginArray(); while(reader.hasNext()){ reader.beginObject(); while(reader.hasNext()){ String tagName = reader.nextName(); if(tagName.equals("name")){ System.out.println("name--->" + reader.nextString()); } else if(tagName.equals("age")){ System.out.println("age--->" + reader.nextInt()); } } reader.endObject(); } reader.endArray(); } catch(Exception e){ e.printStackTrace(); }
解析一个 json 对象到一个自定义对象,例如:
要解析 String jsonData = "{\"name\":\"Michael\",\"age\":20}"; 可以定义 model 类 user public class User { private String name ; privateint age ; public String getName() { return name; } public void setName(String name) { this.name = name; } publicintgetAge() { return age; } public void setAge(int age) { this.age = age; } }
解析过程: Gsongson = new Gson(); User user = gson.fromJson(jsonData, User.class); System.out.println("name--->" + user.getName()); System.out.println("age---->" + user.getAge());
补充:若要解析的 json 数据如下:
{
AList: [ { a1:1, a2:2, a3:3 }, { a1:11, a2:22, a3:33 } ], BList: [ { b1:1, b2:2, b3:3 }, { b1:11, b2:22, b3:33 } ], C: 0 }
可自定义对象如下:
public class Model { private List<A>AList; private List<B>BList; privateint C;
public class A { privateint a1; privateint a2; privateint a3; ......... } public class B { privateint b1; privateint b2; privateint b3; ......... } ........ } //省略了 get set
解析一组 json 对象到自定义对象
例如要解析的数据为: String jsonData = "[{\"name\":\"Michael\",\"age\":20},{\"name\":\"Mike\",\"age\":21}]"; 解析到 user,其定义如上, 解析过程为 public void parseUserFromJson(String jsonData){
Type listType = new TypeToken<LinkedList<User>>(){}.getType (); Gsongson = new Gson(); LinkedList<User> users = gson.fromJson(jsonData, listType); //用迭代器遍历 users for (Iterator iterator = users.iterator(); iterator.hasNext();) { User user = (User) iterator.next(); System.out.println("name--->" + user.getName()); System.out.println("age---->" + user.getAge()); }
and check it : ing-gson-in-java
对象-->JSON
假如我们有一个类 Person:
public class Person { public long public id; name;
String
publicbooleanisMale; public } String avatar;
通过一个 Gson 实例:
Gsongson = new
Gson();
我们可以直接将一个 Person 实例转换成 Json 字符串:
Person person = person.id= 111;
new
Person();
person.name= "张三"; person.isMale= true; person.avatar= "";
String jsonStr = gson.toJson(person); Log.v("=============", jsonStr);
即使是 List 和 Map 也可以(以 List 为例):
ArrayList<Person> list =
new
ArrayList<Person>();
Person person = person.id= 111;
new
Person();
person.name= "张三"; person.isMale= true; person.avatar= ""; list.add(person);
person = new
Person();
person.id= 222; person.name= "李四"; person.isMale= false; person.avatar= "";
list.add(person);
String jsonStr = gson.toJson(list); Log.v("=============", list);