解析json格式的工具类

  1. import java.lang.reflect.Type;
  2. import java.util.HashMap;
  3. import java.util.List;
  4. import java.util.Map;
  5. import org.json.JSONException;
  6. import org.json.JSONObject;
  7. import android.text.TextUtils;
  8. import com.google.gson.Gson;
  9. import com.google.gson.reflect.TypeToken;
  10. /**
  11. * 基于Gson进行解析
  12. * @author Administrator
  13. *
  14. */
  15. public class JsonUtil {
  16. /**
  17. * 把一个map变成json字符串
  18. * @param map
  19. * @return
  20. */
  21. public static String parseMapToJson(Map<?, ?> map) {
  22. try {
  23. Gson gson = new Gson();
  24. return gson.toJson(map);
  25. } catch (Exception e) {
  26. }
  27. return null;
  28. }
  29. /**
  30. * 把一个json字符串变成对象
  31. * @param json
  32. * @param cls
  33. * @return
  34. */
  35. public static <T> T parseJsonToBean(String json, Class<T> cls) {
  36. Gson gson = new Gson();
  37. T t = null;
  38. try {
  39. t = gson.fromJson(json, cls);
  40. } catch (Exception e) {
  41. }
  42. return t;
  43. }
  44. /**
  45. * 把json字符串变成map
  46. * @param json
  47. * @return
  48. */
  49. public static HashMap<String, Object> parseJsonToMap(String json) {
  50. Gson gson = new Gson();
  51. Type type = new TypeToken<HashMap<String, Object>>() {
  52. }.getType();
  53. HashMap<String, Object> map = null;
  54. try {
  55. map = gson.fromJson(json, type);
  56. } catch (Exception e) {
  57. }
  58. return map;
  59. }
  60. /**
  61. * 把json字符串变成集合
  62. * params: new TypeToken<List<yourbean>>(){}.getType(),
  63. *
  64. * @param json
  65. * @param type new TypeToken<List<yourbean>>(){}.getType()
  66. * @return
  67. */
  68. public static List<?> parseJsonToList(String json, Type type) {
  69. Gson gson = new Gson();
  70. List<?> list = gson.fromJson(json, type);
  71. return list;
  72. }
  73. /**
  74. *
  75. * 获取json串中某个字段的值,注意,只能获取同一层级的value
  76. *
  77. * @param json
  78. * @param key
  79. * @return
  80. */
  81. public static String getFieldValue(String json, String key) {
  82. if (TextUtils.isEmpty(json))
  83. return null;
  84. if (!json.contains(key))
  85. return "";
  86. JSONObject jsonObject = null;
  87. String value = null;
  88. try {
  89. jsonObject = new JSONObject(json);
  90. value = jsonObject.getString(key);
  91. } catch (JSONException e) {
  92. e.printStackTrace();
  93. }
  94. return value;
  95. }
  96. }





posted @ 2016-08-08 15:09  杨伟乔  阅读(1455)  评论(0编辑  收藏  举报