My main goal is to get the information out of a JSON file and manipulate it in memory (trying to solve syntax issues in memory). Afterward, parse the manipulated value into an Object with com.google.gson.JsonParser and leave the old File as it was in the beginning (with the syntax errors included).
I managed to manipulate the File with RandomAccessFile and Parse it afterward while using "new FileReader". But after running through the code I noticed that the "old" file was modified and that shouldn't be the case. I don't want to change the file itself but the content and parse it into an Object with JsonParser or whatever Parser there is available for this.
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.RandomAccessFile;
public class JsonLoggingParser {
public static final void main(String[] args) {
String path = "C:\\CEC\\Dev\\logs\\BIMBO\\2019-04-12asdf.json";
parseJsonLogFile(path);
}
public static void parseJsonLogFile(String filePath){
try {
File f = new File(filePath);
RandomAccessFile randomAccessFile = new RandomAccessFile(f, "rw");
randomAccessFile.seek(0);
randomAccessFile.write("[{".getBytes());
randomAccessFile.seek(f.length());
randomAccessFile.write("]".getBytes());
randomAccessFile.close();
JsonParser jsonParser = new JsonParser();
Object object = jsonParser.parse(new FileReader(f));
JsonArray jsonArray = (JsonArray)object;
System.out.println(jsonArray.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is how my JSON file looks like:
{
"788ad1bc-e9c8-4be5-b5b6-26ba011dc40e-request": {
"date": "2019-04-15 10:28:58.943",
"url": "/BIMBO/credit",
"handleType": "request",
"status": "200",
"request": "Hello There",
"response": "",
"performanceDuration": "",
"principalID": "123456789"
}
},{
"788ad1bc-e9c8-4be5-b5b6-26ba011dc40e-response": {
"date": "2019-04-15 10:28:59.125",
"url": "/BIMBO/credit",
"handleType": "response",
"status": "422",
"request": "",
"response": "Hello Back",
"performanceDuration": "218.696979ms",
"principalID": ""
}
}
Basically I need to add a "[" and "]" at the beginning/end of the file to solve the syntax issue.