So I have troubles with creating Json file correctly.
What I have:
1. Gson libs
2. Trying to write in a Json a new user like this:
public static void writeUserBD(String name, String surname, int age) {
//writing in a Json format
JSONObject writeOne = new JSONObject();
JSONArray arr = new JSONArray();
for(int i = 0; i< arr.size() ; i++)
{
writeOne.put("name", name);
writeOne.put("surname", surname);
writeOne.put("age", new Integer(age));
arr.add(writeOne);
writeOne = new JSONObject();
}
//creating dir&file and writing in it
try {
File dir = new File("Test");
dir.mkdir();
File f = new File("Test/TestUser.json");
if (!dir.exists()) {
dir.mkdirs();
} else if (!f.exists()) {
f.createNewFile();
}
//here comes writing encoding problem ! ! !
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f.getAbsoluteFile(), true), Charset.forName("UTF-8")));
try {
bw.write(arr + " " + "\n");
} finally {
bw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
But if I reload my app and try to write a new one it will write a new JSONObject and my output be like :
[{}]
[{}]
In this case i cant parse my json file (for creating simple login) im getting error like "unexcpected token [[]" As I understood this happens becouse of more than 1 jsonobject in a file.
So my question is: how can I write new users data in a json file (even if app was reloaded) in right format that i can pasre than/ for example [{},{},{}]
Try
new FileOutputStream(f.getAbsoluteFile(), false)
true parameter appends to the current file, false should create a new one
The output of your code should be an empty array because you never add an element to the array.
You create a new array and iterate over it. But a new array has no elements and thus the code inside the
loop will never be executed. Beside of that you want to add a new user only once and hence you don't need a loop.
You should read the file first, then add the new user to it and write it back. I created a simple example for you.
I didn't use GSON before, so I'm sure that there is a better way to do this, but it works nevertheless.
I used the try-with-resource feature and the new IO API of Java 7 and did not handle exceptions further. So if you want to handle exceptions
inside the method change the code accordingly. I didn't create the file-structure, so you should do this on your own as well.
public static void writeUserBD(final String name, final String surname, final int age) throws IOException {
final Path jsonFile = Paths.get("Test/TestUser.json");
final JsonArray users = new JsonArray();
// Read all existing users
if (Files.isRegularFile(jsonFile)) {
try (final JsonReader r = new JsonReader(Files.newBufferedReader(jsonFile))) {
r.beginArray();
while (r.hasNext()) {
final JsonObject user = new JsonObject();
r.beginObject();
r.nextName();
user.addProperty("name", r.nextString());
r.nextName();
user.addProperty("surname", r.nextString());
r.nextName();
user.addProperty("age", r.nextInt());
r.endObject();
users.add(user);
}
r.endArray();
}
}
// Create the new user
final JsonObject user = new JsonObject();
user.addProperty("name", name);
user.addProperty("surname", surname);
user.addProperty("age", age);
users.add(user);
// Write all users
try (final BufferedWriter w =
Files.newBufferedWriter(jsonFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
w.write(users.toString());
}
}
Related
I am writing data to a JSON file using a for loop, my question is will all the data be written to the file or a new .json file will be created every time?
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
list.add("xyz");
for (String name : list) {
JSONObject obj = new JSONObject();
obj.put("Name:", name);
try (FileWriter file = new FileWriter("C:\\Users\\elements.json")) {
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
Please update your code like this.
...
FileWriter file = new FileWriter("C:\Users\elements.json")
for (String name : list) {
JSONObject obj = new JSONObject();
obj.put("Name:", name);
file.write(obj.toJSONString());
}
file.flush();
...
Otherwise, please use string variable to store all json as one string variable and write the string variable to file at once.
Instead, you can use Jackson's ObjectMapper to map the entire list object.
List<String> list = new ArrayList<>();
list.add("abc");
list.add("def");
list.add("xyz");
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.writeValue(new File("elements.json"), list);
When the following code is executed, print function prints all the elements within the jsonarray, but the writer, only the first collection of elements.
So far I've tried what is shown in the code, plus, iterating through the list
public class FileWrapper {
public static void WriteRelease(String filename, ArrayList<Object> list) throws IOException, JSONException{
File file = new File(filename);
FileWriter filew = new FileWriter(filename);
JSONArray jsonarray = new JSONArray();
//System.out.println(jsonarray.put(list).toString());
jsonarray.add(list);
System.out.println(jsonarray);
jsonarray.writeJSONString(jsonarray,filew);
filew.close();
}
}
The output I want written in the file is the same as the standard output:
[[Title - Eminem Is Back Status - Bootleg Language - eng
ReleaseDate - 2004-09-28 Format - CD Track Count - 11]] [[Title -
The Eminem Show Status - Official Language - eng ReleaseDate - 2002
Format - Digital Media Track Count - 20]] [[Title - The Eminem Show
Status - Official Language - eng ReleaseDate - 2002 Format -
Digital Media Track Count - 19]]
Again, what is written is only this:
[[Title - Eminem Is Back Status - Bootleg Language - eng
ReleaseDate - 2004-09-28 Format - CD Track Count - 11]]
Turns out, the work around was simple, as noted by #SatyaTNV, the only thing that needed changing was the Filewriter line
By adding
new FileWriter(filename, true)
Everything was printed fine! Thank you based SatyaTNV!
Try this
try (PrintWriter pw = new PrintWriter(writer)) {
pw.println(jsonArray.toString());
}
I am not sure about writing by JSONArray class
Please check my solution:
App.java class
// JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try {
URL resource = App.class.getClassLoader().getResource("info.json");
System.out.println(resource.toString());
FileReader reader = new FileReader(resource.getFile());
// Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray infoList = (JSONArray) obj;
System.out.println(infoList);
Information i = new Information();
List<Information> info = i.parseInformationObject(infoList);
saveInformation(info);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
and iterate:
Information.java class
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}
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
I’m doing a converter from json to csv file. I’ve tried a solution from this link but it doesn’t work properly: Converting JSON to XLS/CSV in Java
The problem is that I don’t have data in separate columns and also I have names of columns in different order. Is it possible to fix this?
My json looks like this:
{
"Code":2,
"Description":"OK",
"Status":0,
"Items":[{ "City":"nameOfCity",
"Country":"nameOfCountry",
"CountryCode":"US",
"Latitude":"11.11111",
"Longitude":"-11.11111",
"Name":"name of Company",
"Region":"nameofRegion",
"ServisID":"111AAA111AA",
"SiteAddress":"number and street 2301",
"ZipCode":"1111"},
{"City":"nameOfCity2",
"Country":"nameOfCountry",
"CountryCode":"US",
"Latitude":"22.22222",
"Longitude":"22.2222222222",
"Name":"name of Company2",
"Region":"nameofRegion",
"ServisID":"111BBB111BB",
"SiteAddress":null,
"ZipCode":null}
, ...etc.
My code:
String bodyStr = new String(proxyResponse.getBody());
JSONObject output;
try {
output = new JSONObject(bodyStr);
JSONArray docs = output.getJSONArray("Items");
File file = new File("C:/folder/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
results(first expected):
image
working as you expect using the below code. I don't see any major difference between your and my code....
public static void main(String[] args) throws IOException {
String inputJson = "{\"Code\":2,\"Description\":\"OK\",\"Status\":0,\"Items\":[{\"City\":\"nameOfCity\",\"Country\":\"nameOfCountry\",\"CountryCode\":\"US\",\"Latitude\":\"11.11111\",\"Longitude\":\"-11.11111\",\"Name\":\"name of Company\",\"Region\":\"nameofRegion\",\"ServisID\":\"111AAA111AA\",\"SiteAddress\":\"number and street 2301\",\"ZipCode\":\"1111\"},{\"City\":\"nameOfCity2\",\"Country\":\"nameOfCountry\",\"CountryCode\":\"US\",\"Latitude\":\"22.22222\",\"Longitude\":\"22.2222222222\",\"Name\":\"name of Company2\",\"Region\":\"nameofRegion\",\"ServisID\":\"111BBB111BB\",\"SiteAddress\":"
+ null + ",\"ZipCode\":" + null + "}]}";
JSONObject objJsonObject = new JSONObject(inputJson);
JSONArray objJsonArray = objJsonObject.getJSONArray("Items");
String csv = CDL.toString(objJsonArray);
FileUtils.writeStringToFile(new File(System.getenv("HOME")+ "/temp.csv"), csv);
}
i opened the csv file using libreoffice v5.1 with UTF-8 encoding
I want to have a json file like this:
{
"resu0":
{"item":"value"}
"resu1":
{"item":"value"}
"resu2":
{"item":"value"}
}
which "resu" and "0,1,2,..." are came from an intent extra.
And I'm using this code for mu purpose:
private void createsome(String str, int pn, String name,String value){
try {
JSONObject koli = new JSONObject();
JSONObject page = new JSONObject();
page.put(name, value);
koli.put(str + pn, page);
File json = new File(mypath,"myfile.json");
FileWriter jsw = new FileWriter(json);
jsw.write(koli.toString());
jsw.flush();
jsw.close();
} catch (Exception e) {
Log.d("Exxx", e.toString());
}
}
But I' getting just the last one and all new jsonobjects are replacing the previous ones instead of adding. for example if I leave the app when my intent number is "5" my whole jsonfile will be like this:
{
"resu5":
{"item":"value"}
}
I know I have a very small misplace problem but I can't find it.
Change
FileWriter jsw = new FileWriter(json);
with
FileWriter jsw = new FileWriter(json, true);
this way thte FileWriter is opened in append mode