Best way to convert multiple byte arrays to a single Java object? - java

EDIT:
I am not sure how much the WHY matters here. There are lot of reasons I am doing what I am doing in a certain way not feasible to explain in one post.
But I will still give some context, the service that stores my json files gives them back as byte arrays, so i start with byte[] arrays, each byte array is a json structure.
From this json i need to convert to a matching JAVA POJO this is POJO serves as a validator and then the final step is using Freemarker generating HTML files out of this POJO.
My scenario is that i get potentially get multiple byte arrays. Each can be a maximum of 500mb. I need to combine them, convert to JSON string and then convert to JAVA POJO.
There are couple of problems i am trying to address:
I see the jsonData only having 1000 records in all.
How do I combine the two jsons into one single json to be then able to convert to JAVA POJO?
Here's my JSON structure:
{
"Header": {
"id": 123
},
"Data": [
{
"key": "123
}
]
}
Here's my current code stripped to bare which I use for BYTE[] -> JSON STRING - > POJO
byte[] dataFile = null;
for (String fileName : getFileNames()) {
try {
byte[] currentFile = null;
currentFile = SomeService.getByteFile(fileName);
dataFile = ArrayUtils.addAll(dataFile, currentFile);
}
String jsonData = new JSONObject(new String(dataFile)).toString();
ObjectMapper mapper = new ObjectMapper();
className classForMapping = mapper.readValue(jsonData, className.class));

Related

InputStream does not seem to read response objects in list

I am trying to read a response from an API endpoint. It works in Postman and appears to work when debugging my java code.
However it will not read any objects that are in the nested array.
I've followed this solution (in the comments someone lays out their solution to accessing objects in a nested array) yet that does not seem to have solved anything as the mapper consistently shows nothing inside the json list.
Here's my code:
try {
response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
final ObjectMapper mapper = new ObjectMapper();
final JsonNode node = mapper.readTree(inputStream);
final JsonNode value = node.get("value");
final JsonNode index = value.get(1);
final String status = index.get("status").asText();
return status;`
}
Here's the response that I'm trying to unpack. I'm trying to get the value of "status"
{
"value": [
{
"activityRunEnd": "2023-01-23T23:22:01.4234985Z",
},
{
"status": "Succeeded"
}
]
}
This is the response that I'm currently getting when I readTree(inputStream)
{"value":[]}
InputStream does not seem to read any values inside the list

How do I make a post request with dynamic values for some attributes stored in external JSON file?

I have a BDD automation framework setup with Selenium WebDriver and Cucumber with Java. I have configured Rest Assured and I am currently using one JSON payload which is stored in an external JSON file. I am directly reading this JSON file into byte array and then converting the same to String and sending the payload to a post request.
Till now, everything was static and hence, this was working without any issue. However, now the requirement is to send a couple of attributes with dynamic values everytime I make a post call. I know how to send a complete dynamic payload using POJOs but I am looking for a different solution where I can read the payload from the same JSON file and can send dynamic values for few required attributes. Please let me know if this is possible.
Attaching the code for reference.
File which reads the JSON file and sends the payload to post request
public class AddOrderAPIActions {
ConfigReader configReader = new ConfigReader();
Properties prop;
public AddOrderAPIActions() {
prop = configReader.init_prop();
}
//Setting up the API URI
public void setURI() {
String URI = prop.getProperty("apiURI");
RestAssured.baseURI = URI;
}
//Sending the request payload via POST method
public String sendRequestPayload() throws IOException {
//read data from local JSON file then store in byte array
byte[] b = Files.readAllBytes(Paths.get("./src/test/resources/data/addOrder.json"));
//convert byte array to string
String bdy = new String(b);
//input details with header and body
Response response = given().header("Content-type", "application/json").queryParam("api_key", prop.getProperty("apiKey")).body(bdy)
//adding post method
.when().post().then().log().all().extract().response();
JsonPath jp = response.jsonPath();
String shipmentNumber = jp.get("data.shipmentDetails[0].shipmentNumber");
System.out.println("Shipment Number is "+ shipmentNumber);
return shipmentNumber;
}
}
The JSON file with payload
[
{
"originDetails": {
"originCode": "Dynamic_Value",
"originStartTime": "",
"originEndTime": "",
"senderName": "Origin Name",
"senderContactNumber": "9999999999",
"senderAddress": "Bali, Indonesia",
"senderPincode": "201001",
"senderCity": "Delhi",
"senderCountry": "India"
},
]
Here, I want to send a dynamic value for "originCode" attribute and rest of the attributes should be sent as read from the JSON file.
Thanks in advance.

Add byte array inside a json object using java

I have below situation. It needs to be implemented in Java.
Take input from a text file, convert the content into a byte array.
Use the above byte array as a part of a JSON object , create a .json file
For point1, i have done something like this.
InputStream is = new ClassPathresource("file.txt").getInputStream();
byte[] ip = IOUtils.toByteArray(is);
For point2, my Json file (containing json object), should look like below.
{
"name": "xyz",
"address: "address here",
"ipdata": ""
}
The ipdata should contain the byte array created in step 1.
How can i create a json object with the byte array created in step 1 as a part of it ? And then write the entire content to a separate .json file ?
Also is the byte array conversion done in step1 an optimum way, or do we need to use any other API(may be to take care of encoding)?Please suggest.
Any help is appreciated. Thanks in advance.
You can simply convert the byte array ip using ip.toString()
Or if you know the encoding you can use ipString = new String(ip, "UTF8")
And then take that string to add to your json object.
Since you are reading a JSON string from file and want to write it back to a new json file you dont need the JSON Object conversion in-between. Just convert the byte[] to String as
String ips = new String(ip);
Now create a JSON Object with the data you want to write to the new file. And then you can write the data to file using FileWriter. PFB the code-
JSONObject obj = new JSONObject();
obj.put("name", "xyz");
obj.put("address", "address here");
obj.put("ipdata", ips);
try(FileWriter fileWriter =
new FileWriter("newFileName.json") ){
fileWriter.write(obj.toString());
}

Json into Array

I am reading a JSON file into one string and one array. I already have a string where the JSON is saved, let's call it myString. Here is the JSON file:
As you can see, the file contains three styles, from "styleCount": "3". My goal is to now create three string variables for each style, similar to the following pseudo variables:
String name_style1 should contain: "Sommer-Fashion"
String name_style2 should contain: "Dream-Style"
String name_style3 should contain: "Perfect-Look"
Then I need an array of strings for each style with the SKU numbers:
private String[] sku_style1 = new String[6];
sku_style1[0] = "392714";
sku_style1[1] = "395895";
sku_style1[2] = "392450";
sku_style1[3] = "371706";
sku_style1[4] = "383748";
sku_style1[5] = "385275";
And also for the other styles:
private String[] sku_style2 = new String[6];
private String[] sku_style3 = new String[6];
Is there a function of Java which helps with simply adding elements from a JSON file (or in my case a string: myString) into a string and an array?
Any help is appreciated.
Google GSON! No functions native to Java really help much, but Google GSON has helped me numerous times with issues much harder than this. I think you'll find it very helpful. Here is a link!
https://mvnrepository.com/artifact/com.google.code.gson/gson
EDIT
This link is for the repository for the jar downloads!
EDIT 2
Gson gson = new Gson();
Staff obj = new Staff();
// 1. Java object to JSON, and save into a file
gson.toJson(obj, new FileWriter("D:\\file.json"));
// 2. Java object to JSON, and assign to a String
String jsonInString = gson.toJson(obj);
There are JSON parson libraries that serve this exact purpose.
JSONArray
JSONString
Read more here.

How to change some values in a .JSON file and then write it back while keeping the JSON formatting ? (Java)

The JSON example file consists of:
{
"1st_key": "value1",
"2nd_key": "value2",
"object_keys": {
"obj_1st": "value1",
"obj_2nd": "value2",
"obj_3rd": "value3",
}
}
I read the JSON file into a String with this StringBuilder method, in order to add the newlines into the string itself. So the String looks exactly like the JSON file above.
public String getJsonContent(String fileName) {
StringBuilder result = new StringBuilder("");
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
Then I translate the JSON file into an Object using MongoDB API (with DBObject, BasicDBObject and util.JSON) and I call out the Object section I need to change, which is 'object_keys':
File jsonFile = new File(C:\\example.json);
String jsonString = getJsonContent(jsonFile.getAbsolutePath());
DBObject jsonObject = (DBObject)JSON.parse(jsonString);
BasicDBObject objectKeys = (BasicDBObject) jsonObject.get("object_keys");
Now I can write new values into the Object using the PUT method like this:
objectKeys.put("obj_1st","NEW_VALUE1");
objectKeys.put("obj_2nd","NEW_VALUE2");
objectKeys.put("obj_3rd","NEW_VALUE3");
! This following part not needed, check out my answer below.
After I have changed the object, I need to write it back into the json file, so I need to translate the Object into a String. There are two methods to do this, either one works.
String newJSON = jsonObject.toString();
or
String newJSON = JSON.serialize(jsonObject);
Then I write the content back into the file using PrintWriter
PrintWriter writer = new PrintWriter(C:\\example.json)
writer.print(newJSON);
writer.close();
The problem I am facing now is that the String that is written is in a single line with no formatting whatosever. Somewhere along the way it lost all the newlines. So it basically looks like this:
{"1st_key": "value1","2nd_key": "value2","object_keys": { "obj_1st": "NEW_VALUE1","obj_2nd": "NEW_VALUE2","obj_3rd": "NEW_VALUE3", }}
I need to write the JSON file back in the same format as shown in the beginning, keeping all the tabulation, spaces etc.
Is this possible somehow ?
When you want something formatted the way you said it is addressed as writing to a file in a pretty/beautiful way. For example: Output beautiful json. A quick search on google found what i believe to solve your problem.
Solution
You're going to have to use a json parser of some sort. I personally prefer org.json and would recommend it if you are manipulating the json data, but you may also like json-io which is really good for json serialization with no external dependencies.
With json-io, it's as simple as
String formattedJson = JsonWriter.formatJson(jsonObject.toString())
With org.json, you simply pass an int to the toString method.
Thanks Saraiva, I found a surprisingly simple solution by Googling around with the words 'pretty printing JSON' and used the Google GSON library. I downloaded the .jar and added it to my project in Eclipse.
These are the new imports I needed:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
Since I already had the JSON Object (jsonObject) readily available from my previous code, I only needed to add two new lines:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String newJSON = gson.toJson(jsonObject);
Now when I use writer.print(newJSON); it will write the JSON in the right format, beautifully formatted and indented.

Categories