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

44 lines
1.5 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 JSONObject getJsonFromGson(JsonObject jsonObject) {
return new JSONObject().getJSONObject(jsonObject.toString());
}
public 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 JsonObject getFixtureDataFrom(String filename) throws IOException {
String json = getJsonAsString(filename);
return new Gson().fromJson(json, JsonObject.class);
}
public String getJsonAsString(String filename) throws IOException {
BufferedReader reader = null;
InputStream inputStream =
getClass().getResourceAsStream("/relative/path/%s.json");
if (inputStream != null) {
reader = new BufferedReader(new InputStreamReader(inputStream));
} else {
throw new IOException("%s.json not found, or has no content.");
}
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
}
}