All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.litongjava.tio.utils.json.GsonJson Maven / Gradle / Ivy

There is a newer version: 3.7.3.v202400213-RELEASE
Show newest version
package com.litongjava.tio.utils.json;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;

public class GsonJson extends Json {

  private Gson gson = new Gson();

  @Override
  public String toJson(Object object) {
    return gson.toJson(object);
  }

  @Override
  public byte[] toJsonBytes(Object object) {
    return gson.toJson(object).getBytes(StandardCharsets.UTF_8);
  }

  @Override
  public  T parse(String jsonString, Class type) {
    return gson.fromJson(jsonString, type);
  }

  @Override
  public Map parseToMap(String json) {
    Type mapType = new TypeToken>() {
    }.getType();
    return gson.fromJson(json, mapType);
  }

  @Override
  public  Map parseToMap(String json, Class kType, Class vType) {
    Type mapType = new TypeToken>() {
    }.getType();
    return gson.fromJson(json, mapType);
  }

  @Override
  public Object parseObject(String jsonString) {
    @SuppressWarnings("deprecation")
    JsonParser parser = new JsonParser();
    @SuppressWarnings("deprecation")
    JsonElement jsonElement = parser.parse(jsonString);
    return jsonElement.getAsJsonObject();
  }

  @SuppressWarnings("deprecation")
  @Override
  public Object parseArray(String jsonString) {
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    return jsonElement.getAsJsonArray();
  }

  @Override
  public  List> parseToListMap(String stringValue, Class kType, Class vType) {
    Type mapType = new TypeToken>() {
    }.getType();
    JsonArray jsonArray = JsonParser.parseString(stringValue).getAsJsonArray();
    List> listMap = new ArrayList<>();

    for (JsonElement jsonElement : jsonArray) {
      Map map = gson.fromJson(jsonElement, mapType);
      listMap.add(map);
    }

    return listMap;
  }

  @Override
  public Object parse(String stringValue) {
    return gson.fromJson(stringValue, Object.class);
  }

  @Override
  public  T parse(String body, Type type) {
    try {
      return gson.fromJson(body, type);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  public  T parse(byte[] body, Type type) {
    try {
      String bodyString = new String(body);
      return gson.fromJson(bodyString, type);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy