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

com.devebot.opflow.OpflowJsontool Maven / Gradle / Ivy

There is a newer version: 0.3.1
Show newest version
package com.devebot.opflow;

import com.devebot.opflow.exception.OpflowJsonTransformationException;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import java.lang.reflect.Type;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author drupalex
 */
public class OpflowJsontool {
    private static final Logger LOG = LoggerFactory.getLogger(OpflowJsontool.class);
    private static final Gson GSON = new Gson();
    private static final JsonParser JSON_PARSER = new JsonParser();
    
    public static String toString(Object jsonObj) {
        return GSON.toJson(jsonObj);
    }
    
    public static String toString(Object[] objs, Type[] types) {
        JsonArray array = new JsonArray();
        for(int i=0; i jsonMap) {
        return GSON.toJson(jsonMap);
    }
    
    public static  T toObject(String json, Class type) {
        return GSON.fromJson(json, type);
    }
    
    public static  T toObject(OpflowMessage message, Class type) {
        return GSON.fromJson(message.getBodyAsString(), type);
    }
    
    public static Map toObjectMap(String json) {
        try {
            Map map = GSON.fromJson(json, Map.class);
            return map;
        } catch (JsonSyntaxException e) {
            throw new OpflowJsonTransformationException(e);
        }
    }
    
    public static Object[] toObjectArray(String arrayString, Class[] types) {
        if (arrayString == null) return new Object[0];
        JsonArray array = JSON_PARSER.parse(arrayString).getAsJsonArray();
        Object[] args = new Object[types.length];
        for(int i=0; i T extractField(String json, String fieldName, Class type) {
        try {
            JsonObject jsonObject = (JsonObject)JSON_PARSER.parse(json);
            return type.cast(jsonObject.get(fieldName));
        } catch (ClassCastException e) {
            throw new OpflowJsonTransformationException(e);
        } catch (JsonSyntaxException e) {
            throw new OpflowJsonTransformationException(e);
        }
    }
    
    public static int extractFieldAsInt(String json, String fieldName) {
        try {
            JsonObject jsonObject = (JsonObject)JSON_PARSER.parse(json);
            return jsonObject.get(fieldName).getAsInt();
        } catch (JsonSyntaxException e) {
            throw new OpflowJsonTransformationException(e);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy