1.通过主Activity的Button按钮实现数据的解析
public class MainActivity extends Activity {
//定义一个包含Json格式的字符对象 private String Data="{"name":"小张","age":25,"sex":"男"};{"name":"小李子","age":41,"sex":"女"};" + "{"name":"倩倩","age":15,"sex":"女"}"; protected void onCreate(Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button=(Button) super.findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { public void onClick(View v) { new JsonUtils(Data); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
2.解析json数据的业务类
public class JsonUtils { public JsonUtils(String jsonData) {
//创建一个google的Gson对象 Gson gson=new Gson();
//根据主Activity传来的数据将数据拆分成Json格式的字符数组对象
//没拆分之前是一个整体"{"name":"小张","age":25,"sex":"男"};{"name":"小李子","age":41,"sex":"女"};"
//拆分之后是一个个单独的字符串对象格式正好符合JSON格式的标准"{"name":"小张","age":25,"sex":"男"}" ; {"name":"小李子","age":41,"sex":"女"}
String[] users=jsonData.split(";"); for(int i=0;i<users.length;i++) {
//创建一个User类对象,第一个参数是json格式的数据,第二个参数是实现数据解析的类对象 User user=gson.fromJson(users[i], User.class); System.out.println(user.getName()+","+user.getAge()+","+user.getSex()); }
上面的方法还可以这样写:
2
但是强调一点是在主Activity的Data的数据是Json格式:
"[{"name":"小张","age":25,"sex":"男"},{"name":"小李子","age":41,"sex":"女"},{"name":"倩倩","age":15,"sex":"女"}]"
而不再是字符串格式
"{"name":"小张","age":25,"sex":"男"};{"name":"小李子","age":41,"sex":"女"};{"name":"倩倩","age":15,"sex":"女"}
" 这样的,注意观察我用红色标注的地方,上面的是json格式的数据是以[(中括号)开始的,下面的字符串是以{(大括号)开始的,而且每一组
({"name":"小张","age":25,"sex":"男"}这样的称为一组数据)的结尾是不同的一个是逗号,一个是分号注意这些细节
Gson gson=new Gson();
Type listpyte=new TypeToken< LinkedList<User> >(){}.getType();
3 LinkedList<User> users=gson.fromJson(jsonData, listpyte); 4 5 for(Iterator<User> iterator=users.iterator();iterator.hasNext();) 6 { 7 User user=(User) iterator.next(); 8 System.out.println(user.getName()+","+user.getAge()+","+user.getSex()); 9 }
}
}
3.实现数据解析的类对象也就是这里的User类
1 public class User 2 { 3 private String name; 4 private int age; 5 private String sex; 6 public String getName() 7 { 8 return name; 9 } 10 11 public void setName(String name) 12 { 13 this.name = name; 14 } 15 16 public int getAge() 17 { 18 return age; 19 } 20 21 public void setAge(int age) 22 { 23 this.age = age; 24 } 25 26 public String getSex() 27 { 28 return sex; 29 } 30 31 public void setSex(String sex) 32 { 33 this.sex = sex; 34 } 35 }
4.运行之前要把Google的Gson-xxx.jar文件拷到项目中的libs文件夹下;这样之后才可以正常的运行