Issue
I am pretty new to Java and have an issue that I don't know how to fix. I read a few tutorials, posted questions etc. but I was still not able to understand how to Transfer the knowledge Fixing my Problem.
Here to Problem.
I want to read multiple json files all at one place and convert the data to Strings. I am able to read one data entry in the json, but not more. :-|
The file data Looks as follows:
{
"Header":{
"Liste1": {
"ID": "12345",
"Name" : "customerlist",
"Company List": [
"Company": "c1",
"Company": "c2",
"Company": "c3"
]
},
"Liste2":{
"ID": "12346",
"Name" : "vendorlist",
"Company List": [
"Company": "c4",
"Company": "c5",
"Company": "c6"
]
}
}
}
The code I used Main:
package testpaket;
import com.google.gson.Gson;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class test6 {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("test.json")) {
// Convert JSON to Java Object
Header header = gson.fromJson(reader, Header.class);
System.out.println(header);
// Convert JSON to JsonElement, and later to String
/*JsonElement json = gson.fromJson(reader, JsonElement.class);
String jsonInString = gson.toJson(json);
System.out.println(jsonInString);*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
My Lists class.
package testpaket;
import java.util.List;
public class Lists {
private String List;
private int ID;
private String Name;
private List<String> companyList;
}
My Header class.
package testpaket;
import java.util.Map;
public class Header {
String name;
String list;
int id;
String header1;
private Map<String, Lists> header;
//getters&setters
public String getHeader() {
return this.header1;
}
public void setHeader(String header) {
this.header1 = header1;
}
public String getList() {
return this.list;
}
public void setList(String list) {
this.list = list;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getID() {
return this.id;
}
public void setID(int id) {
this.id = id;
}
}
Does any of that even make sense? Sorry, but I really tried transfering the knowledge I have so far. Could anyone please help me and tell me how to fix it?
Solution
If you want to convert JSON-files to strings, it is not necessary to convert the file to a Java Object and after to a String. With apache commons-io library you can do this with only 1 line.
String exampleRequest = FileUtils.readFileToString(new File("exampleJsonRequest.json"), StandardCharsets.UTF_8);
Answered By - salvatore rinaudo
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)