I’m writing a code that reads a file which is in json and convert it do hashtable.
However I’m having a NullPointerException when i try to convert String to hashtable.
readBackInfo = gson.fromJson(readjsonString, fileInfoType);
Here’s the code I’m implementing
public void readSyncFile(){
String readjsonString = null;
readBackInfo = new HashMap<String, ArrayList<String[]>>();
try {
FileInputStream fstream = new FileInputStream(_dirName+"/."+_dirName);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if(readjsonString==null){
readjsonString = strLine;
} else {
readjsonString = readjsonString + "\n" + strLine;
}
}
in.close();
//System.out.println(readjsonString);
Type fileInfoType = new TypeToken<HashMap<String, ArrayList<String[]>>>() {}.getType();
System.out.println(allFiles.isEmpty());
//getting a NullPointerException from the line below!
readBackInfo = gson.fromJson(readjsonString, fileInfoType);
sFileInToHashtable();
//readjsonString = gson.toJson(readBackInfo);
//System.out.println(readjsonString);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Nothing is setting
readjsonStringbetween:and:
So the first exception you’re catching is expected, and what you are doing is not good practice at all. If
readjsonStringbeing null is expected (as it is here), check for that.It would be even better if you used StringBuilder – that’s what it’s for.
The second NPE will happen exactly there only if
gsonis null. That variable is not defined or set in what you posted, so can’t know if this is possible or not.If the exception is occurring inside the
fromJsonmethod call, it could be because you read no input at all andreadjsonStringwould thus still be null. So switch to a StringBuilder and stop using exceptions for normal flow control and you should be ok.If this doesn’t solve your problems, you’ll need to post the stack trace.