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);
Related
My dependency which is not third party
<dependency>
<groupId>javax.json</groupId>
<artifactId>javax.json-api</artifactId>
<version>1.1.4</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.4</version>
</dependency>
JSon array test
[{"name":"aondx","value":10,"date":"1999-01-09T14:30:53Z"}]
I am able to parse/ write into the a create a csv file but the issue is it is not in the right format in my csv file.
public static void writeFilteredJsonToNewFile(JsonArray jsonArray) {
try {
for (Object object : jsonArray) {
JsonObject obj = (JsonObject) object;
StringWriter writer = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(writer);
jsonWriter.writeObject(obj);
writer.close();
FileWriter fileWriter = new FileWriter(diretory + name + ".csv");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(writer.toString());
bufferedWriter.close();
System.out.println("Created new File!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Result
Expected result (table format) in a csv file
name
value
date
aondx
40
1999-01-09T14:30:53Z
If my understanding is correct, you want to convert the json into csv file but while writing to csv you are getting key value in each row instead of key in the first row and then value in the subsequent rows.
I think if you follow below steps then you will able to achieve this:
1) First convert your Json into the List<Map<String,String>> using below code
> ObjectMapper mapper = new ObjectMapper();
> List<Map<String, Object>> datas = mapper.readValue(jsonArray.toString(), new
> TypeReference<List<Map<String, Object>>>(){});
2) Find the keys from the json, which will be used as your column, assuming all the data having same keys.
> Set<String> columns = datas.get(0).keySet(); write columns as the
> first row in the csv file.
3) Iterate over the datas list and start writing the value row wise.
As you mentioned in the comment you doesn't not want to use the external library then instead of ObjectMapper you can use your JsonArray.
Instead of converting your json Array to List<Map<String,String>> and getting the keys you can do the same thing with JsonObject only as it implement Map only.
Set<String> columns = jsonArray.get(0).keySet();
this code should be before you are starting the loop.
Inside the loop you are iterating over the jsonArray, there read the value .
Set<String> columns = jsonArray.get(0).keySet();
for (Object object : jsonArray) {
JsonObject obj = (JsonObject) object;
List<String> dataRows = new ArrayList();
for(String column : columns ) {
String value = (String)obj.get(column);
dataRows.add(value);
}
.......
// write the value to file
.......
}
If you are Interested in full solution, you can try this.
public static void writeFilteredJsonToNewFile(JsonArray jsonArray) {
List<List<String>> allDatas = new ArrayList<>();
Set<String> columns = jsonArray.get(0).keySet();
allDatas.add(new ArrayList<>(columns));
for (Object object : jsonArray) {
JsonObject obj = (JsonObject) object;
List<String> dataRows = new ArrayList();
for(String column : columns ) {
String value = (String)obj.get(column);
dataRows.add(value);
}
allDatas.add(dataRows);
}
writeToCsvFile(allDatas,",","test-file.csv");
}
public void writeToCsvFile(List<List<String>> thingsToWrite, String separator, String fileName){
try (FileWriter writer = new FileWriter(fileName)){
for (List<String> strings : thingsToWrite) {
for (int i = 0; i < strings.size(); i++) {
writer.append(strings[i]);
if(i < (strings.length-1))
writer.append(separator);
}
writer.append(System.lineSeparator());
}
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
How can I convert a List object in Java to a JSON object?
For example, how can I convert this:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2):
...
To this JSON:
{
"List" : [1, 2, ...]
}
Thank you!
If you want just to convert the list to json, you can use Gson:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
String json = new Gson().toJson(myList);
If you want that the key will be "List", you need to create a object with a member that call List and then convert it.
If you need to convert to String use the com.fasterxml.jackson.databind.ObjectMapper
Ex:
List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(myList);
System.out.println("result = " + json);
//System.out.println(json);
} catch (JsonProcessingException e) {
//
}
I am writing my data to csv file in java. Below is my code
public static void writeAccountToFile(List<Map<String, Object>> list, String filePath) {
System.out.println("Write data to csv file start");
try {
File file = new File(filePath);
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
CsvSchema schema = null;
CsvSchema.Builder schemaBuilder = CsvSchema.builder();
if (list != null && !list.isEmpty()) {
for (String col : list.get(0).keySet()) {
schemaBuilder.addColumn(col);
}
schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
}
CsvMapper mapper = new CsvMapper();
mapper.writer(schema).writeValues(writer).writeAll(list);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Write data to csv file end");
}
When I check my result file, last line there is no "" in accountName test3 and test4.
accountId,accountName,address
1111,"test1111111",england
2222,"test222222222",tokyo
3333,test3,italy
4444,test4,indo
Here is my input list:
[{accountId=1111, accountName=test1111111, address=england}, {accountId=2222,
accountName=test222222222, address=tokyo}, {accountId=3333, accountName=test3,
address=italy}, {accountId=4444, accountName=test4,
address=indo}]
Here is my code to read csv file and assign it to list:
public static List<Map<String, Object>> loadFileAccount(String filePath) throws Exception {
List<Map<String, Object>> list = new ArrayList<>();
removeBom(Paths.get(filePath));
System.out.println("Load account data from csv start");
File file = new File(filePath);
Reader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");
Iterator<Map<String, Object>> iterator = new CsvMapper()
.readerFor(Map.class)
.with(CsvSchema.emptySchema().withHeader())
.readValues(reader);
while (iterator.hasNext()) {
Map<String, Object> keyVals = iterator.next();
list.add(keyVals);
}
reader.close();
System.out.println("Load account data from csv end");
return list;
}
What is error in my code?
It seems that you are right, when the String is long, it adds quotes.
So to avoid inconsistencies, you can specify if you want quotes or not using
CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS or CsvGenerator.Feature.STRICT_CHECK_FOR_QUOTING
This will always add double quotes:
CsvMapper mapper = new CsvMapper();
mapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);
mapper.writer(schema).writeValues(writer).writeAll(list);
The other one should never add double quotes
All type of json elements like objects in json files arrays and simple key value pairs.
When you call JSONParser parser = new JSONParser(); obj = parser.parse(path);
parser.parse() expects an actual JSON string, not the path to the JSON file.
It wants to see something like this:
json.parse("{ "name":"John", "age":31, "city":"New York" }");
To fix your code, you can do this:
List < String > list = new ArrayList < >();
try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) {
//br returns as stream and convert it into a List
list = br.lines().collect(Collectors.toList());
} catch(IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
for (String s: list) {
sb.append(s);
}
String json = sb.toString()
JSONParser parser = new JSONParser();
obj = parser.parse(json);
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());
}
}