Appending jsonobject to an existing jsonobject - java

I'm having a problem with Json file reading and writing. I want to append something into a json file but it doesn't work properly: it just put in a new jsonobject without the ',' to divide it from the previous one. I searched everywhere, on every site, but nothing that gave me an input on how to do it properly.
For example, I have a json file like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}
And I want to make it appear like this:
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
So, I tried using this code:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonObject jsonObject = new JsonObject();
JsonObject dati = new JsonObject();
dati.addProperty("Cognome", StringUtils.capitalize((fields[0].getText())));
dati.addProperty("Nome", StringUtils.capitalize((fields[1].getText())));
dati.addProperty("Sesso", lblSesso.getText());
dati.addProperty("Luogo di nascita", StringUtils.capitalize((fields[2].getText())));
dati.addProperty("Provincia", lblProvincia.getText());
dati.addProperty("Data di nascita", fieldDDN.getText());
jsonObject.add(codfis, dati);
String json = gson.toJson(jsonObject);
try (BufferedReader br = new BufferedReader(new FileReader("CodFisCalcolati.json"));
BufferedWriter bw = new BufferedWriter(new FileWriter("CodFisCalcolati.json", true))) {
String jsonString = gson.fromJson(br, JsonElement.class).toString();
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobject = jelement.getAsJsonObject();
jobject.add(codfis, dati);
String resultingJson = gson.toJson(jelement);
bw.write(resultingJson);
bw.close();
} catch (IOException e1) { e1.printStackTrace(); }
But when I use it, it give me this output :
{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
}
}{
"Example":{
"Ok":"Ok1",
"Nice":"Nice1",
"Hi":"Hi1",
"Hello":"Hello1",
"Right":"Right1",
"Wow":"Wow1"
},
"Example1":{
"Ok":"Ok2",
"Nice":"Nice2",
"Hi":"Hi2",
"Hello":"Hello2",
"Right":"Right2",
"Wow":"Wow2"
}
}
That's output, you see, it'wrong and i don't know how to make the code to give me a different output.
I'm using Gson 2.8.5 and I would rather not change to another library.

You change the question but now the answer to your new question is you use the same file to read and write. That's why you add the data inside ot the file. Change the name of the file that you write and see if you have problems

Please check if "br" is not null.
According to the specification of the method fromJson it returns:
an object of type T from the string. Returns null if json is null.
If this is the case than you call on the null toString() method and you get null pointer exception

Related

Java: How to go about return values in a try-catch?

I am somewhat in doubt about how to go about returning a value in a catch-block, when I really don't want the catch-block to return a value at all.
I am trying to make a java class 'User', that has a method for creating a user account and saving it to a json file, like so:
private void saveAsJson() {
JSONObject newUser = new JSONObject();
newUser.put("name", this.name);
newUser.put("lastName", this.lastName);
newUser.put("password", this.password);
System.out.println(newUser);
try {
File jsonFile = new File("./data/Account.json");
fileIsEmpty(jsonFile); //void method checking if file is empty or already contains data.
getJsonArray(jsonFile);//method that should parse the contents of the jsonfile to a JSONArray.
//More code...
///
...
private JSONArray getJsonArray(File sourceFile) {
try {
FileReader fr = new FileReader(sourceFile);
JSONTokener tk = new JSONTokener(fr);
JSONObject jsonObj = new JSONObject(tk);
JSONArray jsonArr = jsonObj.getJSONArray("Accounts");
return jsonArr;
} catch (Exception e) {
System.out.println("Unable to read accounts in getJsonArray.");
return *what to return??*;
}
}
The Method JSONArray is simply meant to read the json file, and return the array. The FileReader class demands that I use a try-catch, in case an exception happens while trying to read the file.
However, when that exception would happen, I don't want the method to return anything at all. The method is already called in a try-block, so I would want this parent try-block to handle the exception, in stead of carrying on with a return value from the method.
How should I go about this. What sort of value should I return? Something like JSONArray fakeArray = new JSONArray(); return fakeArray;? What happens when that value is returned, does saveAsJson() carry on with that empty array, and mess up the structure of my json file?
To be clear: I do understand that and why there must be a return value. The method getJsonArray simply expects a JSONArray to be returned. I do not know how to best handle this.
Don't catch the Exception. Declare that the method throws instead and have the caller of the method catch it.
// It's better to declare the specific type of the Exception instead of bare Exception
private JSONArray getJsonArray(File sourceFile) throws Exception {
FileReader fr = new FileReader(sourceFile);
JSONTokener tk = new JSONTokener(fr);
JSONObject jsonObj = new JSONObject(tk);
JSONArray jsonArr = jsonObj.getJSONArray("Accounts");
return jsonArr;
}

When streaming a Json file with GSON's JsonReader, can you dump an object to string?

I am working in Java using the GSON library to process a huge JSON document.
I absolutely cannot load this into memory, it is upwards of 8G and will crash the JVM with an OOM if I try to.
So I use JsonReader to process the stream of JSON.
There are certain times when I reach a BEGIN_OBJECT that want to just dump the contents of the object to string instead of processing each individual element.
For example, I am parsing something like this:
[ { "SchemaVersion":"15.0.0.0","LibraryVersion":"16.0.7324.1200","ErrorInfo":{ "ErrorMessage":"Access denied. You do not have permission to perform this action or access this resource.","ErrorValue":null,"TraceCorrelationId":"03ab459e-7076-5000-c1a7-196f1fc54384","ErrorCode":-2147024891,"ErrorTypeName":"System.UnauthorizedAccessException" },"TraceCorrelationId":"03ab459e-7076-5000-c1a7-196f1fc54384" } ]
When I get to ErrorInfo, I just want that as a string instead of parsed out. I don't want to have to parse each piece.
So here is the code:
try (InputStream is = (InputStream)response.getEntity();
InputStreamReader inputStreamReader = new InputStreamReader(is);
JsonReader jsonReader = new JsonReader(inputStreamReader)) {
if (jsonReader.peek() != JsonToken.BEGIN_ARRAY) {
return;
}
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject(); // Start of the default object on every request
jsonReader.skipValue(); // name SchemaVersion
jsonReader.skipValue(); // value
jsonReader.skipValue(); // name LibraryVersion
jsonReader.skipValue(); // value
jsonReader.skipValue(); // name ErrorInfo
if (jsonReader.peek() == JsonToken.BEGIN_OBJECT) {
// I want to dump the upcoming object to string here
...
Is it possible to dump the contents of the json reader for a given begin object until it ends to string?
Similar question, but not quite the same: Get a dump of a section (object) of JSON
Special thanks to https://stackoverflow.com/users/3389828/nikhil for the answer in the comments. You can use Gson.fromJson(jsonReader, Map.class) for this exact situation.
Gson gson = new Gson();
try (InputStream is = (InputStream)response.getEntity();
InputStreamReader inputStreamReader = new InputStreamReader(is);
JsonReader jsonReader = new JsonReader(inputStreamReader)) {
if (jsonReader.peek() != JsonToken.BEGIN_ARRAY) {
return;
}
jsonReader.beginArray();
while (jsonReader.hasNext()) {
Map header = gson.fromJson(jsonReader, Map.class);
if (header.get("ErrorInfo") != null) {
String errorDump = ((Map)header.get("ErrorInfo")).toString();
// Now I have the error dump I need but I also
// didn't load the entire thing into memory!
...
more info: https://javadeveloperzone.com/java-8/java-parse-large-json-file-gson-example/

Why is JsonObject empty despite the string provided in its constructor being correct?

So, I am trying to make a JsonObject using org.json library, from a string.
This is the code I am using:
StringBuilder line = new StringBuilder();
while (fScanner.hasNextLine()) {
line.append(fScanner.nextLine());
}
System.out.println(line);
JSONObject jsonObject = new JSONObject(line);
System.out.println(jsonObject.toString());
But the output I am getting is showing, empty JsonObject but correct string. It looks like this:
{"username": "Sam","name": "Sam Anderson","points": "150"}
{}

Unexpected token END OF FILE at position 0 while parsing JSON

In order to find out weather the JSON element is JSONArray or JSONObject type, I am getting Unexpected token END OF FILE at position 0 error.
My JSON is:
{"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
My code is:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
System.Out.Println("aaaaaa JSON Class: "+parser.parse(reader).getClass());
if(parser.parse(reader) instanceof org.json.simple.JSONArray)
System.Out.Println("JSONArray");
else if(parser.parse(reader) instanceof org.json.simple.JSONObject)
System.Out.Println("JSONObject");
When I run above code it shows this output
aaaaaa JSON Class: class org.json.simple.JSONObject Unexpected token END OF FILE at popsition 0
at org.json.simple.parser.JSONParser(Unknown Source)
.
.
.
<rest of the exception>
I don't understand why this exception is occurring.
Please help me out.
Some more details after edit:
My this code is working fine with the given json file:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
org.json.simple.JSONObject object = (JSONObject)parser.parse(reader);
System.Out.Println("JSONObject: "+object);
org.json.simple.JSONArray array = (JSONArray)object.get("colors");
System.Out.Println("JSONArray: "+array);
Output of above code:
JSONObject: {"colors":[{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]}
JSONArray: [{"color":"red","value":"#00"},{"color":"white","value":"#000g"}]
But I want to dynamically parse the JSON without knowing the JSON structure.
I want to do something like this:
if(json is object)
JSONObject object = (JSONObject)parser.parse(reader);
else if (json is array)
JSONArray array = (JSONArray)parser.parse(reader);
Thanks.
You're repeatedly parsing the same Reader. The first call exhausts it and then each subsequent call sees an empty stream.
Parse the reader only once. Here is the working code:
java.io.FileReader reader = new java.io.FileReader("jsonpath");
org.json.simple.parser.JSONParser parser = new JSONParser();
Object p = parser.parse(reader);
if(p instanceof org.json.simple.JSONArray){
System.Out.Println("JSONArray");
org.json.simple.JSONArray object = (JSONArray)p;
}
else if(p instanceof org.json.simple.JSONObject){
System.Out.Println("JSONObject");
org.json.simple.JSONObject object = (JSONObject)p;
}
Output of above code
JSONObject
Well, error may occur when you try to pass wrong path.
So check your path to json file properly. Try to use absolute path at first.
Here is my procedure:
private static void ReadWithEncoding(String filePath, String encoding) {
StringBuilder json = new StringBuilder();
File f = new File(filePath);
if (f.exists() && f.isFile()) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), encoding));
String line;
while ((line = br.readLine()) != null) {
json.append(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(json);
}
}
You may run it like this for UTF8:
ReadWithEncoding("D:/file.json", "UTF8");
For Cyrillic symbols:
ReadWithEncoding("D:/file.json", "Cp1251");
I too was getting this error ("Unexpected token END OF FILE at position 0.").
I was using same instance of com.google.gson.Gson and org.json.simple.parser.JSONParser on multiple threads.
Now I changed the code and created new instance of these on each thread, and that solved the issue.
gson = new GsonBuilder().create();
parser = new JSONParser();

getString not working for JSON key

I'm learning how to work with JSON's in java and I'm having a problem using getString for one of my keys. My code is here:
public static void getJSON(String matchID){
String s = "";
String test = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try {
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
String[] items = new String[stuff.length()];
items[0] = stuff.getString("firstName");
} catch (JSONException e) {
e.printStackTrace();
}
}
The "getString" is underlined in red, and the "The method getString(int) in the type JSONArray is not applicable for the arguments (String)" I was following an answer to another question word for word almost, and this happens, any advice? Thanks!
EDIT:
I need to get the specifics by name ie. "firstName" because I will be working with thousands of JSONs that each have hundreds of lines.
You need to get the JSOnObject first from the JSONArray(stuff) before you can call getString().
if you want to get the first element in the jsonarray and get its string this is how you would do it
JsonObject obj = stuff.getJsonObject(0);
String name = obj.getString("firstname");
So I figured out my problem, I didn't realize I had an JSONObject first, my apologies. Fixed like this:
JSONObject hi = new JSONObject(test);
JSONArray stuff = hi.getJSONArray("employees");
JSONObject name = stuff.getJSONObject(0);
String[] items = new String[hi.length()];
items[0]=name.getString("firstName");
System.out.println(items[0]);
you can try the simplest way to Parse in JSON
JSONParser parser=new JSONParser();
String s = "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"}]}";
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
System.out.println(array.get(1));
}catch(ParseException pe){
}

Categories