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

43 lines
1.6 KiB
Java
Raw Normal View History

2023-07-12 13:14:52 +00:00
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 {
2023-07-19 09:17:00 +00:00
public static JSONObject getJsonFromGson(JsonObject gJsonObject) {
return new JSONObject(gJsonObject.toString());
2023-07-12 13:14:52 +00:00
}
2023-07-19 09:17:00 +00:00
public static JSONObject getJsonFromDataTable(DataTable dataTable) {
2023-07-12 13:14:52 +00:00
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);
}
2023-07-19 09:17:00 +00:00
public static JsonObject getFixtureDataFrom(String filename) throws IOException {
2023-07-12 13:14:52 +00:00
String json = getJsonAsString(filename);
return new Gson().fromJson(json, JsonObject.class);
}
2023-07-19 09:17:00 +00:00
private static String getJsonAsString(String filename) throws IOException {
2023-07-12 13:14:52 +00:00
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.");
2023-07-12 13:14:52 +00:00
}
}