java-utilities/src/main/java/com/gmgauthier/JsonUtils.java

43 lines
1.6 KiB
Java

package com.gmgauthier;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.cucumber.datatable.DataTable;
import kong.unirest.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class JsonUtils {
public static JSONObject getJsonFromGson(JsonObject gJsonObject) {
return new JSONObject(gJsonObject.toString());
}
public static JSONObject getJsonFromDataTable(DataTable dataTable) {
List<Map<String, String>> tableDetails =
dataTable.transpose().asMaps(String.class, String.class);
String bodyString = new Gson().toJson(tableDetails.get(0)); //root element
return new JSONObject(bodyString);
}
public static JsonObject getFixtureDataFrom(String filename) throws IOException {
String json = getJsonAsString(filename);
return new Gson().fromJson(json, JsonObject.class);
}
private static String getJsonAsString(String filename) throws IOException {
InputStream inputStream =
JsonUtils.class
.getResourceAsStream(
String.format("/com/gmgauthier/fixtures/%s.json",filename));
if (inputStream != null)
return new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining(System.lineSeparator()));
else throw new IOException("%s.json not found, or has no content.");
}
}