服务器返回客户端的数据有两种:XML,Json数据(轻量级)。
Json本质上是String。
下面讲解在服务器生成Gson数据以及在客户端解析Gson数据的过程:
1、服务器端返回Gson数据:
List<String> list = service.getMsg();
out.print(gsonutlis.createGsonString(list));
gsonutlis.java代码:
public class gsonutlis { public static String createGsonString(Object value){ Gson gson=new Gson(); String result=gson.toJson(value); return result; } }
2、客户端接收Gson数据并解析:
String result = HttpClientUtils.sendHttpclientGet(null, CommonUrl.Get_Msg, CommonUrl.eccode); List<String> list = GsonUlits.getListFromGson(result);
GsonUlits.java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.znufe.service.CommonUrl; public class GsonUlits { // 从一个json获取一个T对象并返回T,如一个用户的基本信息 public static <T> T getObjectFromJson(String jsonString, Class<T> cls) { // import java.lang.reflect.Type; // import com.google.gson.reflect.TypeToken; T t = null; try { Gson gson = new Gson(); t = gson.fromJson(jsonString, cls); } catch (Exception e) { // TODO: handle exception } return t; } // 从一个json获取一个List<T>对象并返回,如多个用户的基本信息 public static <T> List<T> getObjectsFromJson(String jsonString, Class<T> cls) { List<T> list = new ArrayList<T>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<T>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } // TypeToken:反射机制 return list; } public static Map<String, Object> getKeyapFromGson(String jsonString) { Map<String, Object> map = new HashMap<String, Object>(); Gson gson = new Gson(); try { map = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return map; } // 相当与getObjectsFromJson的泛型T=String public static List<String> getListFromGson(String jsonString) { List<String> list = new ArrayList<String>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<String>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list; } public static List<Map<String, Object>> getListKeyapFromGson( String jsonString) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); try { Gson gson = new Gson(); list = gson.fromJson(jsonString, new TypeToken<List<Map<String, Object>>>() { }.getType()); } catch (Exception e) { // TODO: handle exception } return list; } }
Done!