package com.inspect.patrol.linkage.util;

import com.alibaba.fastjson.JSONObject;

import java.util.Iterator;
import java.util.Set;

public class JsonUtil {
    public static JSONObject str2Json(String... args) {
        return str2Json(JSONObject.class, args);
    }

    public static <T> T str2Json(Class<T> t, String... args) {
        JSONObject result = new JSONObject();
        for (String arg : args) {
            String[] split = arg.split("=");
            result.put(split[0], split[1]);
        }

        return result.toJavaObject(t);
    }

    public static String json2Str(JSONObject json) {
        if (json.isEmpty()) {
            return "";
        } else {
            Set<String> keys = json.keySet();
            StringBuilder sb = new StringBuilder();

            for (String key : keys) {
                sb.append(key).append("=").append(json.getString(key)).append("&");
            }

            return sb.substring(0, sb.length() - 1);
        }
    }
}
