I'm getting a JSON array in string like
[ { "id":"ca.Primary_Diagnosis_Dt",
"field":"ca.Primary_Diagnosis_Dt",
"type":"date",
"input":"text",
"operator":"not_equal",
"value":"2016/06/07"
},
{ "id":"ca.Clinical_Stage",
"field":"ca.Clinical_Stage",
"type":"integer",
"input":"select",
"operator":"equal",
"value":"I"
}
]
i just want to save the value of id ,operator and value in LIST please help
Online : Working code
First create a class to store your values :
class Data{
String id;
String operator;
String value;
}
Then iterate over the json :
JSONArray jsonArr = new JSONArray("[JSON Stirng]");
List<Data> dataList = new ArrayList<>();
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
Data data = new Data();
data.id = jsonObj.getString("id");
data.operator = jsonObj.getString("operator");
data.value = jsonObj.getString("value");
dataList.add(data);
}
Now dataList has your data!
P.S. : Use getter/setters in Data class
JAR : http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm
Use any JSON parsor eg: GSON to create an arraylist of this particular json
Iterate the arraylist
Save it :)
You can do that with a JSon library such as org.glassfish.javax.json
In Maven use
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.0.4</version>
</dependency>
Then read the string to a JsonArray:
JsonArray ja = Json.createReader(new StringReader(input)).readArray();
Then iterate over the list, map the objects to a new objects with just the values you need:
List<JsonObject> list = ja.stream()
.map(o -> (JsonObject) o)
.map(jo -> Json.createObjectBuilder()
.add("id", jo.getJsonString("id"))
.add("operator", jo.getJsonString("operator"))
.add("value", jo.getJsonString("value")).build())
.collect(Collectors.toList());
In case you could not use JsonObject as output, you may use a value object instead - just like Himanshu Tyagi proposed - and map the values to that object.
In your case, I think, the JSON should be parsed into a List<Map<String,String>>. This can be done using Jackson. Following is a method that converts a JSON string into List<Map<String,String>>:
public static List<Map<String, String>> toList(String json) throws IOException {
List<Map<String, String>> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<HashMap<String, String>>>() {
});
return listObj;
}
If you have created a POJO class for it then you can use:
public static List<PojoClass> toList(String json) throws IOException {
List<PojoClass> listObj;
ObjectMapper MAPPER = new ObjectMapper();
listObj = MAPPER.readValue(json, new TypeReference<ArrayList<PojoClass>>() {
});
return listObj;
}
Maven dependency for Jackson:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
Related
I have an Object array which is a list of argument values a function could take. This could be any complex object.
I am trying to build a json out of the Object array using gson as below:
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
Arrays.stream(argVals).forEach(arg -> argsArray.add(gson.toJson(arg)));
return argsArray;
}
This treats all the arg values as String.
It escapes the String args
"args":["\"STRING\"","1251996697","85"]
I prefer the following output:
"args":["STRING",1251996697,85]
Is there a way to achieve this using gson?
I used org.json, I was able to achieve the desired result, but it does not work for complex objects.
EDIT:
I applied the solution provided by #Michał Ziober, but now how do I get back the object.
Gson gson = new Gson();
Object strObj = "'";
JsonObject fnObj = new JsonObject();
JsonObject fnObj2 = new JsonObject();
fnObj.add("response", gson.toJsonTree(strObj));
fnObj2.addProperty("response", gson.toJson(strObj));
System.out.println(gson.fromJson(fnObj.toString(),
Object.class)); --> prints {response='} //Not what I want!
System.out.println(gson.fromJson(fnObj2.toString(),
Object.class)); --> prints {response="\u0027"}
Use toJsonTree method:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
GsonApp app = new GsonApp();
System.out.println(app.createArgsJsonArray("text", 1, 12.2D));
System.out.println(app.createArgsJsonArray(new Date(), new A(), new String[] {"A", "B"}));
}
private Gson gson = new GsonBuilder().create();
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
for (Object arg : argVals) {
argsArray.add(gson.toJsonTree(arg));
}
return argsArray;
}
}
class A {
private int id = 12;
}
Above code prints:
["text",1,12.2]
["Sep 19, 2019 3:25:20 PM",{"id":12},["A","B"]]
If you want to end up with a String, just do:
private String createArgsJsonArray(Object... argVals) {
Gson gson = new Gson();
return gson.toJson(argVals);
}
If you wish to collect it back and alter just do:
Object[] o = new Gson().fromJson(argValsStr, Object[].class);
Try using setPrettyPrinting with DisableHtml escaping.
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonArray.toString());
System.out.println( gson.toJson(je));
if I have to following XML document info into a string:
<Collection>
...
<Places><D>USA</D><D>BRAZIL</D><D>COREA</D></Places>
...
</Collection>
and I want to convert it into a Json that look something like:
{
"PLACES": ["USA", "BRAZIL", "COREA"]
}
Note that the <D> tags are ignored and i get the values inside of them as the values that I want into my array... How do I do that in java? I'm doing the following using org.json and jackson API:
String xml = FileUtils.readFileToString(new File(file.getAbsolutePath()));
JSONObject json = org.json.XML.toJSONObject(xml);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT)
Object json2 = mapper.readValue(json.toString(), Object.class);
String output = mapper.writeValueAsString(json2);
System.out.println(output);
but it converts the info like this:
{
"PLACES" : {
"D" : [ "USA", "BRAZIL", "COREA" ]
}
So I want the array to be directly after "PLACES", ignoring that "D"... any suggestion? Thanks
Use XmlMapper to convert xml into POJO. Even you don't need to read file manually.
POJO (Collection class)
#JacksonXmlRootElement(localName = "Collection")
public class Collection {
#JsonProperty("PLACES")
#JacksonXmlProperty(localName = "D")
#JacksonXmlElementWrapper(localName = "Places")
List<String> places;
public List<String> getPlaces() {
return places;
}
public void setPlaces(List<String> places) {
this.places = places;
}
}
Main Method
public static void main(String[] args) throws Exception {
ObjectMapper xmlMapper = new XmlMapper();
xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);
Collection c = xmlMapper.readValue(new File("/root/config.txt"), Collection.class);
System.out.println(xmlMapper.writeValueAsString(c));
ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.enable(SerializationFeature.INDENT_OUTPUT);
System.out.println(jsonMapper.writeValueAsString(c));
}
Output
<Collection>
<Places>
<D>USA</D>
<D>BRAZIL</D>
<D>COREA</D>
</Places>
</Collection>
{
"PLACES" : [ "USA", "BRAZIL", "COREA" ]
}
Xml library
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.5</version>
</dependency>
SimpleXml and Gson can do it:
public class Collection {
public Places Places;
}
public class Places {
#SerializedName("PLACES")
public List<String> D;
}
final String data = ...
final SimpleXml simple = new SimpleXml();
final Collection c = simple.fromXml(data, Collection.class);
final Gson gson = new Gson();
System.out.println(gson.toJson(c.Places));
Will output:
{"PLACES":["USA","BRAZIL","COREA"]}
From maven central:
<dependency>
<groupId>com.github.codemonstur</groupId>
<artifactId>simplexml</artifactId>
<version>1.4.0</version>
</dependency>
BTW if you don't like the naming you can change anything using SimpleXml annotations. I didn't need them so I didn't use them.
I know this question or similar ones have been asked multiple times here, but I swear I've read tons of related posts and none of the solutions seems to be working for me.
I'm trying to map some JSON data, which I receive from a specific REST API, to a Java class. The JSON has this format:
{"netStatLinks":[
{"src":"of:0000000000000002/3",
"dst":"of:0000000000000000/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{"src":"of:0000000000000005/3",
"dst":"of:0000000000000006/1",
"bw":10000.0,
"rate":0.0,
"usage":0.0,
"available":10000.0},
{...and so on}
]}
The Java class I want to map the JSON to is this:
public class NetStatLinkList {
private List<NetStatLink> netStatLinks;
// Generated getter and setter
#Override
public String toString(){
return netStatLinks.toString();
}
}
and
public class NetStatLink {
public String src;
public String dst;
public double bw;
public double rate;
public double usage;
public double available;
public NetStatLink(String src, String dst, double bw, double rate, double usage, double available){
this.src = src;
this.dst = dst;
this.bw = bw;
this.rate = rate;
this.usage = usage;
this.available = available;
}
// Generated getters and setters
#Override
public String toString() {
return "Link "+src +"to"+ dst+" -- "+"rate: "+rate;
}
}
I can read the JSON correctly but I can't manage to map it in any way. I've tried all this options without success (note that url is an URL object created based on the url string and that all the neccessary exceptions are implicitly catched):
Using Jackson to directly map the JSON to NetStatLinkList
ObjectMapper mapper = new ObjectMapper();
NetStatLinkList linkLst = mapper.readValue(url,NetStatLinkList.class);
Using Jackson to map the JSON to a List of NetStatLink objects
TypeReference<List<NetStatLink>> type = new TypeReference<List<NetStatLink>>() {};
List<NetStatLink> linkLst = mapper.readValue(url, mapType);
Using Jackson to map the JSON string directly to the class/to a List of objects
JsonNode rootNode = mapper.readValue(url,JsonNode.class);
JsonNode data = rootNode.get("netStatLinks");
List<NetStatLink> linkLst = mapper.readValue(data.toString(), mapType);
// or
NetStatLink[] linkLst = mapper.readValue(data.toString(), NetStatLink[].class)
// or
List<NetStatLink> linkLst = mapper.readValue(data.traverse(), mapType);
Using Jackson to map the JSON to an ArrayNode and iterate through it
JsonNode linkData = mapper.readTree(url);
ArrayNode linkDataArray = (ArrayNode)linkData.get("netStatLinks");
List<NetStatLink> linkLst;
while(linkDataArray.elements().hasNext()){
linkLst.add(mapper.readValue(linkDataArray.elements().next().toString(),NetStatLink.class));
}
Using the external library json-simple to read the JSON and then map it with Jackson
String location = IOUtils.toString(url);
JSONObject jo = (JSONObject) JSONValue.parseWithException(location);
JSONArray val = (JSONArray) jo.get("NetStatLinks");
List<NetStatLink> linkLst = mapper.readValue(val.toJSONString(), mapType);
// or
NetStatLink[] linksList = mapper.readValue(val.toJSONString(), NetStatLink[].class);
Do you know if there's any other way I could map this JSON data to my classes, or if there's any mistake in those methods which is the reason I cannot get them to work?
You can use gson
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.1</version>
</dependency>
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("netStatLinks");
List<NetStatLink> users = new ArrayList<NetStatLink>();
Gson gson = new Gson();
Type listType = new TypeToken<List<NetStatLink>>(){}.getType();
netStatLink = gson.fromJson(jsonArr ,listType);
I created a simple POJO:
public class LoginPojo {
private String login_request = null;
private String email = null;
private String password = null;
// getters, setters
}
After some searching I found this: JSONObject jsonObj = new JSONObject( loginPojo );
But with this I got the error:
The constructor JSONObject(LoginPojo) is undefined
I found another solution:
JSONObject loginJson = new JSONObject();
loginJson.append(loginPojo);
But this method does not exist.
So how can I convert my POJO into a JSON?
Simply use the java Gson API:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(obj);// obj is your object
And then you can create a JSONObject from this json String, like this:
JSONObject jsonObj = new JSONObject(json);
Take a look at Gson user guide and this SIMPLE GSON EXAMPLE for more information.
It is possible to get a (gson) JsonObject from POJO:
JsonElement element = gson.toJsonTree(userNested);
JsonObject object = element.getAsJsonObject();
After that you can take object.entrySet() and look up all the tree.
It is the only absolutely free way in GSON to set dynamically what fields you want to see.
Jackson provides JSON parser/JSON generator as foundational building block; and adds a powerful Databinder (JSON<->POJO) and Tree Model as optional add-on blocks. This means that you can read and write JSON either as stream of tokens (Streaming API), as Plain Old Java Objects (POJOs, databind) or as Trees (Tree Model). for more reference
You have to add jackson-core-asl-x.x.x.jar, jackson-mapper-asl-x.x.x.jar libraries to configure Jackson in your project.
Modified Code :
LoginPojo loginPojo = new LoginPojo();
ObjectMapper mapper = new ObjectMapper();
try {
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
// Setting values to POJO
loginPojo.setEmail("a#a.com");
loginPojo.setLogin_request("abc");
loginPojo.setPassword("abc");
// Convert user object to json string
String jsonString = mapper.writeValueAsString(loginPojo);
// Display to console
System.out.println(jsonString);
} catch (JsonGenerationException e){
e.printStackTrace();
} catch (JsonMappingException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Output :
{"login_request":"abc","email":"a#a.com","password":"abc"}
JSONObject input = new JSONObject(pojo);
This worked with latest version.
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
You can also use project lombok with Gson overriding toString function. It automatically includes builders, getters and setters in order to ease the data assignment like this:
User user = User.builder().username("test").password("test").build();
Find below the example class:
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import com.google.gson.Gson;
#Data
#Builder(toBuilder = true)
#AllArgsConstructor
#NoArgsConstructor
public class User {
/* User name. */
private String username;
/* Password. */
private String password;
#Override
public String toString() {
return new Gson().toJson(this, User.class);
}
public static User fromJSON(String json) {
return new Gson().fromJson(json, User.class);
}
}
Simply you can use the below solution:
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(loginPojo);
JSONObject jsonObject = new JSONObject(str);
I use jackson in my project, but I think that u need a empty constructor.
public LoginPojo(){
}
You can use
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
To create a JSON object:
#Test
public void whenGenerateJson_thanGenerationCorrect() throws ParseException {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < 2; i++) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("AGE", 10);
jsonObject.put("FULL NAME", "Doe " + i);
jsonObject.put("DATE OF BIRTH", "2016/12/12 12:12:12");
jsonArray.add(jsonObject);
}
String jsonOutput = jsonArray.toJSONString();
}
Add the annotations to your POJO class like so:
#JSONField(name = "DATE OF BIRTH")
private String dateOfBirth;
etc...
Then you can simply use:
#Test
public void whenJson_thanConvertToObjectCorrect() {
Person person = new Person(20, "John", "Doe", new Date());
String jsonObject = JSON.toJSONString(person);
Person newPerson = JSON.parseObject(jsonObject, Person.class);
assertEquals(newPerson.getAge(), 0); // if we set serialize to false
assertEquals(newPerson.getFullName(), listOfPersons.get(0).getFullName());
}
You can find a more complete tutorial on the following site:
https://www.baeldung.com/fastjson
I just want to convert a string that contains a yaml into another string that contains the corrseponding converted json using Java.
For example supose that I have the content of this yaml
---
paper:
uuid: 8a8cbf60-e067-11e3-8b68-0800200c9a66
name: On formally undecidable propositions of Principia Mathematica and related systems I.
author: Kurt Gödel.
tags:
- tag:
uuid: 98fb0d90-e067-11e3-8b68-0800200c9a66
name: Mathematics
- tag:
uuid: 3f25f680-e068-11e3-8b68-0800200c9a66
name: Logic
in a String called yamlDoc:
String yamlDoc = "---\npaper:\n uuid: 8a... etc...";
I want some method that can convert the yaml String into another String with the corresponding json, i.e. the following code
String yamlDoc = "---\npaper:\n uuid: 8a... etc...";
String json = convertToJson(yamlDoc); // I want this method
System.out.println(json);
should print:
{
"paper": {
"uuid": "8a8cbf60-e067-11e3-8b68-0800200c9a66",
"name": "On formally undecidable propositions of Principia Mathematica and related systems I.",
"author": "Kurt Gödel."
},
"tags": [
{
"tag": {
"uuid": "98fb0d90-e067-11e3-8b68-0800200c9a66",
"name": "Mathematics"
}
},
{
"tag": {
"uuid": "3f25f680-e068-11e3-8b68-0800200c9a66",
"name": "Logic"
}
}
]
}
I want to know if exists something similar to the convertToJson() method in this example.
I tried to achieve this using SnakeYAML, so this code
Yaml yaml = new Yaml();
Map<String,Object> map = (Map<String, Object>) yaml.load(yamlDoc);
constructs a map that contain the parsed YAML structure (using nested Maps). Then if there is a parser that can convert a map into a json String it will solve my problem, but I didn't find something like that neither.
Any response will be greatly appreciated.
Here is an implementation that uses Jackson:
String convertYamlToJson(String yaml) {
ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
Object obj = yamlReader.readValue(yaml, Object.class);
ObjectMapper jsonWriter = new ObjectMapper();
return jsonWriter.writeValueAsString(obj);
}
Requires:
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.7.4')
Thanks to HotLicks tip (in the question comments) I finally achieve the conversion using the libraries org.json and SnakeYAML in this way:
private static String convertToJson(String yamlString) {
Yaml yaml= new Yaml();
Map<String,Object> map= (Map<String, Object>) yaml.load(yamlString);
JSONObject jsonObject=new JSONObject(map);
return jsonObject.toString();
}
I don't know if it's the best way to do it, but it works for me.
Big thanks to Miguel A. Carrasco he infact has solved the issue. But his version is restrictive. His code fails if root is list or primitive value. Most general solution is:
private static String convertToJson(String yamlString) {
Yaml yaml= new Yaml();
Object obj = yaml.load(yamlString);
return JSONValue.toJSONString(obj);
}
I found the example did not produce correct values when converting Swagger (OpenAPI) YAML to JSON. I wrote the following routine:
private static Object _convertToJson(Object o) throws JSONException {
if (o instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>) o;
JSONObject result = new JSONObject();
for (Map.Entry<Object, Object> stringObjectEntry : map.entrySet()) {
String key = stringObjectEntry.getKey().toString();
result.put(key, _convertToJson(stringObjectEntry.getValue()));
}
return result;
} else if (o instanceof ArrayList) {
ArrayList arrayList = (ArrayList) o;
JSONArray result = new JSONArray();
for (Object arrayObject : arrayList) {
result.put(_convertToJson(arrayObject));
}
return result;
} else if (o instanceof String) {
return o;
} else if (o instanceof Boolean) {
return o;
} else {
log.error("Unsupported class [{0}]", o.getClass().getName());
return o;
}
}
Then I could use SnakeYAML to load and output the JSON with the following:
Yaml yaml= new Yaml();
Map<String,Object> map= (Map<String, Object>) yaml.load(yamlString);
JSONObject jsonObject = (JSONObject) _convertToJson(map);
System.out.println(jsonObject.toString(2));
I was directed to this question when searching for a solution to the same issue.
I also stumbled upon the following article https://dzone.com/articles/read-yaml-in-java-with-jackson
It seems Jackson JSON library has a YAML extension based upon SnakeYAML.
As Jackson is one of the de facto libraries for JSON I thought that I should link this here.
Thanks, Miguel! Your example helped a lot. I didn't want to use the 'JSON-java' library. I prefer GSON. But it wasn't hard to translate the logic from JSON-java over to GSON's domain model. A single function can do the trick:
/**
* Wraps the object returned by the Snake YAML parser into a GSON JsonElement
* representation. This is similar to the logic in the wrap() function of:
*
* https://github.com/stleary/JSON-java/blob/master/JSONObject.java
*/
public static JsonElement wrapSnakeObject(Object o) {
//NULL => JsonNull
if (o == null)
return JsonNull.INSTANCE;
// Collection => JsonArray
if (o instanceof Collection) {
JsonArray array = new JsonArray();
for (Object childObj : (Collection<?>)o)
array.add(wrapSnakeObject(childObj));
return array;
}
// Array => JsonArray
if (o.getClass().isArray()) {
JsonArray array = new JsonArray();
int length = Array.getLength(array);
for (int i=0; i<length; i++)
array.add(wrapSnakeObject(Array.get(array, i)));
return array;
}
// Map => JsonObject
if (o instanceof Map) {
Map<?, ?> map = (Map<?, ?>)o;
JsonObject jsonObject = new JsonObject();
for (final Map.Entry<?, ?> entry : map.entrySet()) {
final String name = String.valueOf(entry.getKey());
final Object value = entry.getValue();
jsonObject.add(name, wrapSnakeObject(value));
}
return jsonObject;
}
// everything else => JsonPrimitive
if (o instanceof String)
return new JsonPrimitive((String)o);
if (o instanceof Number)
return new JsonPrimitive((Number)o);
if (o instanceof Character)
return new JsonPrimitive((Character)o);
if (o instanceof Boolean)
return new JsonPrimitive((Boolean)o);
// otherwise.. string is a good guess
return new JsonPrimitive(String.valueOf(o));
}
Then you can parse a JsonElement from a YAML String with:
Yaml yaml = new Yaml();
Map<String, Object> yamlMap = yaml.load(yamlString);
JsonElement jsonElem = wrapSnakeObject(yamlMap);
and print it out with:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
System.out.println(gson.toJson(jsonElem));
Using Gson:
var yaml = new YAML();
var gson = new Gson();
var reader = new FileReader(path.toFile());
var obj = yaml.load(reader);
var writer = new StringWriter();
gson.toJson(obj, writer);
String result = writer.toString();
Spring boot with kotlin to return a yaml file content as json data
package br.com.sportplace.controller
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.InputStream
#RestController
#RequestMapping(value = ["resources/docs"])
class DocsController {
#GetMapping(produces = ["application/json"])
fun load(): ResponseEntity<Any> {
return getResourceFileAsString()
}
fun getResourceFileAsString(): ResponseEntity<Any> {
val inputStream = getResourceFileAsInputStream("openapi/api.yaml")
return if (inputStream != null) {
val objectMapper = ObjectMapper(YAMLFactory())
ResponseEntity.ok(objectMapper.readValue(inputStream, Any::class.java))
} else {
ResponseEntity(ErrorResponse(), HttpStatus.INTERNAL_SERVER_ERROR)
}
}
fun getResourceFileAsInputStream(fileName: String?): InputStream? {
val classLoader = DocsController::class.java.classLoader
return classLoader.getResourceAsStream(fileName)
}
private data class ErrorResponse(
val message: String = "Failed to load resource file",
val success: Boolean = false,
val timestamp: Long = System.currentTimeMillis()
)
}