Ok i am creating an application that used JSON to save date. I used GSON as my JSON "processor".
Yes i know how to use Gson. I follow the tutorial on web. The problem is, the tutorial on web and only save "one" json data. I mean, for example,
{
"Data1": {
"name": "Data1",
"info": "ABCDEFG"
}
}
So, after user saved Data1, they want to save Data2, Data3, etc like this
{
"Data1": {
"name": "Data1",
"info": "ABCDEFG"
},
"Data2": {
"name": "Data2",
"info": "ABCDEFGHIJ"
}
}
But if user want to save 100+ data do i have to make 100 classes? Below are my code.
JSONTest.class
public class JSONTest
{
private static Gson gson;
private static File file;
private static JSONTest instance;
private static Bean bean;
private static Map<String, String> data = new HashMap();
public static void main(String[] args)
{
bean = new Bean();
File file = new File("C://test-json.json");
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
gson = builder.create();
data.put("name", "data1");
data.put("info", "abcde");
bean.setData(data);
String jsonString = gson.toJson(bean);
try
{
FileWriter fw = new FileWriter(file);
fw.write(jsonString);
fw.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Bean.class
public class Bean
{
private Map<String, String> data;
public Map<String, String> getData()
{
return data;
}
public void setData(Map<String, String> properties)
{
this.data = properties;
}
}
So the result is this
{
"data": {
"name": "data1",
"info": "abcde"
}
}
ok now i change the value(mean that i want to add new data
data.put("name", "data2");
data.put("info", "abcdef");
bean.setData(data);
the result is this
{
"data": {
"name": "data2",
"info": "abcdef"
}
}
but i want the result like this
{
"data1": {
"name": "data1",
"info": "abcde"
},
"data2": {
"name": "data2",
"info": "abcdef"
}
}
So my question is, how can i do that?If user want to save 100+ data do i have to make 100+classes or elements? And also, how to add "selectedData: "data1"" so my json loader so load 1 data only?
Map<String, YourClass>would work here.