Gson解析json

public static String CreateJsonStringbyGson(Object value) {
		Gson gson = new Gson();
		String Str = gson.toJson(value);
		return Str;

	}
public class JsonService {
	//一个person对象
	public Person getPerson(){
		Person person=new Person(1001,"hang","suqian");
		return person;
	}
	
	public List getlistPerson(){
		List list=new ArrayList();
		Person person1=new Person(1001,"zhang","suqian");
		Person person2=new Person(2002,"hang","yangzhou");
		list.add(person1);
		list.add(person2);
		
		return list;
		
	}
	public List getlistString(){
		List list=new ArrayList();
		list.add("beijing");
		list.add("suqian");
		return list;
	}
	
	public List> getlistMap(){
		List> list=new ArrayList>();
		Map map1=new HashMap();
		map1.put("id", 1001);
		map1.put("name","zhang");
		map1.put("address", "beijing");
		Map map2=new HashMap();
		map2.put("id", 1002);
		map2.put("name","hang");
		map2.put("address", "shanghai");
		list.add(map1);
		list.add(map2);
		return list;
	}

}

android客户端解析

package com.example.andorid_json;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.widget.EditText;

public class GsonTools {

	public static  T getPerson(String jsonString, Class cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return t;
	}

	public static  List getPersons(String jsonString, Class cls) {
		List list = new ArrayList();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken>() {
			}.getType());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public static List getList(String jsonString) {
		List list = new ArrayList();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;

	}
	public static List> listKeyMap(String jsonString){
		List> list=new ArrayList>();
		try {
			Gson gson = new Gson();
			list = gson.fromJson(jsonString, new TypeToken>>() {
			}.getType());
		} catch (Exception e) {
			// TODO: handle exception
		}
		return list;
	}
	
	
}


你可能感兴趣的:(android)