I am storing an arraylist of Objects in JSON format in a file. As soon as new arraylist appears it converts the object in JSON format and append it in the file.The encoding works fine. But while decoding it throws exception. I am quite new in this field and learning.Any help is welcome.
Encoding Code
public static void jsondumpfile(ArrayList<HtmlElementObject> sanitizelog)
{
try {
File file = new File("c:\\temp\\auditinfojson.json");
if(!file.exists()){
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file,true);
BufferedWriter bw = new BufferedWriter(fileWriter);
Gson gson=new Gson();
//bw.append("---------------");
//bw.append(gson.toJson(sanitizelog));
//fw.append(gson.toJson(sanitizelog));
for(HtmlElementObject eachobj : sanitizelog)
{
bw.write(gson.toJson(eachobj));
}
//bw.flush();
bw.close();
logElementData.clear();
} catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
RESULTANT FILE AFTER ENCODING {"appLoginId":1058,"tabId":"1","elementType":"Image","label":"No Image Name","value":"https://admin.xyz.com","seqTrail":"No possible trail sequence","timeStamp":"2014-01-31 13:02:42.618"} {"appLoginId":1058,"tabId":"1","elementType":"Image","label":"No Image Name","value":"https://admin.xyz.com/xyz/images/btn-cancel.gif","seqTrail":"No possible trail sequence","timeStamp":"2014-01-31 13:02:42.625"}
Like this multiple objects are stored.
DECODING/PARSING BACk CODE
public static void extractfromjson() throws IOException
{
ArrayList<HtmlElementObject> tCollection = new ArrayList<HtmlElementObject>();
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"c:\\temp\\auditinfojson.json"));
Type type = new TypeToken<ArrayList<HtmlElementObject>>(){}.getType();
ArrayList<HtmlElementObject> J_tweet = (ArrayList<HtmlElementObject>)gson.fromJson(bufferedReader, type);
System.out.println(J_tweet);
}
EXCEPTION THROWN **com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2** This comes when i want to retrieve the data.
HtmlElementObjectas one by one json object to file, But while reading your reading asArrayList. Either you have to Write asArrayListand read asArrayListOR write one by one object and read them one by one. May be to read them one by one.