Java Gson 的使用

项目地址: https://github.com/google/gson

maven 引入jar包

<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.2</version>
</dependency>

Gson 中 Java对象转成JSON字符串

public class GsonnUtils
{
  private static Gson gson = new GsonBuilder().create();

  public static String jsonEcode(Object obj) {
      return gson.toJson(obj);
  }
}

Gson 中 JSON字符串转成Java对象

public class GsonnUtils
{
  private static Gson gson = new GsonBuilder().create();

  public static <T> T jsonDecode(String jsonStr, Class<T> objClass) {
      return gson.fromJson(jsonStr, objClass);
  }
}

Java Gson 工具类

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class GsonUtils {

  private static Gson gson = new GsonBuilder().create();

  public static String jsonEcode(Object obj) {
      return gson.toJson(obj);
  }

  public static <T> T jsonDecode(String jsonStr, Class<T> objClass) {
      return gson.fromJson(jsonStr, objClass);
  }
}