How can I read and write from and to a JSON file? - java

So I tried to write some code using what I found out on different sites but nothing works. Every time I try to write in to the file it doesn't work.
Here is the code for writing and reading from and in a JSON file:
HashMap<Word, ArrayList<Word>> map=null;
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("Dictionar.json"));
JSONObject jsonObject = (JSONObject) obj;
map=(HashMap) jsonObject;
} catch (Exception e) {
e.printStackTrace();
}
Dictionar dictionar=new Dictionar();
dictionar.setDictionar(map);
Here is the code for writing to the file:
JSONObject obj = new JSONObject();
obj.putAll(dictionar);
File f=new File("Dictionar.json");
f.createNewFile();
FileWriter file = new FileWriter(f);
obj.writeJSONString(file);
System.out.println("Successfully Copied JSON Object to File...");
System.out.println("\nJSON Object: " + obj);
}
catch (IOException i) {
i.printStackTrace();
}
The variable dictionar is a HashMap.

Related

Jersey RESTful: How to populate DAO with a local json file?

this is my first time building a Jersey Restful web service.
The project is supposed to be a server that provides information about Reddit posts. For now, this information is stored in a large JSON file, and because it is not supposed to be manipulated, my idea is to store this information in the dao class in form of Post instances.
here is my projects' folder organisation: filesView
So my idea is to populate the dao class by reading the json file something like this:
public enum PostDao {
instance;
private Map<String, Post> posts = new HashMap<String, Post>();
private PostDao() {
//JSON parser object to parse read file
System.out.println("init");
JSONParser jsonParser = new JSONParser();
try {
FileReader reader = new FileReader("src/main/resources/data/posts.json");
//Read JSON file
Object obj = jsonParser.parse(reader);
JSONArray postsArr = (JSONArray) obj;
for (Object p : postsArr) {
JSONObject post = (JSONObject) p;
Post pobj = new Post(post.get("title"), post.get("author"));
posts.put(pobj.getId(), pobj);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
public Map<String, Post> getModel() {
return posts;
}
The problem is that I do not know where to put the json file and what the path would be.
Is there a standard folder and path to store this kind of files? Or is there a different way to populate the dao class?
I managed to find a solution which was pretty simple:
JSONParser jsonParser = new JSONParser();
try {
//get JSON file's path
InputStream in = this.getClass().getResourceAsStream("/data/posts.json");
BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
//Read JSON file
Object obj = jsonParser.parse(br.readLine());
for (Object p : (JSONArray) obj) {
JSONObject post = (JSONObject) p;
//add post to mapping
this.addPost(new Post(generateId(),
(String)post.get("user"),
(String)post.get("title"),
(String)post.get("date")));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Note: my json file consisted of only one line (as text file) so that is why BufferedReader.readLine() was enough

Get JSONArray and write to JSONArray

I have the following object:
{
"some_prop": "sweetvalue",
"some_list": ["0f9f822cd7e64000ac056ebc17b82f1d", "0f9f82223094fj7b82f1d"]
}
And I'm trying to get some_list and write to some_list, afterwards saving to a file. using the following code:
public String getData(String key) { // this is confusion should be getConfigValue
String data = getConfig();
JSONObject jsonData;
Object content = null;
try {
jsonData = new JSONObject(data);
if (key != null) {
content = jsonData.getString(key);
} else {
content = jsonData.toString();
}
} catch (JSONException e) {
e.printStackTrace();
}
return content.toString();
}
private void saveFile(String data) {
File file = configFile;
try (FileOutputStream fop = new FileOutputStream(file)) {
if (!file.exists()) file.createNewFile();
byte[] contentInBytes = data.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void appendToArrayValue(String uuid) {
JSONObject configData = new JSONObject(getConfig());
JSONArray mutedPlayers = configData.getJSONArray("some_list");
JSONArray uuidArray = new JSONArray(uuid);
JSONArray newArray = concatArray(mutedPlayers, uuidArray);
JSONObject newConfigData = configData.put("some_list", newArray);
saveFile(newConfigData.toString());
}
When trying to run this code, I get the following error:
org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
I'm not sure what's really wrong, I know my code is terrible but that's it.
Looks like the error is at line JSONArray uuidArray = new JSONArray(uuid);?
Because prevoius line JSONArray mutedPlayers = configData.getJSONArray("some_list"); should work fine.
If so, you are passing not an array to new JSONArray(uuid) since uuid is your whole JSON object.

trying to write nested JSON into File

It's my first post here.
Well, I got a problem trying to write nested JSON into File in Android.
It show me a java.lang.StackOverflowError.
My question is: Is there any way to write a nested JSON into file without having any kind of problem with stack.
I'll show you nested JSON and the way I'm trying to write into the File
JSONObject fingerPrint = new JSONObject();
try {
fingerPrint.put("fingerPrint", fingerPrint);
} catch (JSONException e) {
Log.v(TAG, "Error parsing creating JSON \"fingerPrint\"");
e.printStackTrace();
}
JSONObject fingerPrintMaterial = new JSONObject();
try {
fingerPrintMaterial.put("methodType", FingerprintFacade.MAC_SHA256);
fingerPrintMaterial.put("keySize", 5);
} catch (JSONException e) {
Log.v(TAG, "Error parsing creating JSON \"fingerPrintMaterial\"");
e.printStackTrace();
}
JSONObject userFingerPrint = new JSONObject();
try {
userFingerPrint.put("fingerPrint", fingerPrint);
userFingerPrint.put("fingerPrintMaterial", fingerPrintMaterial);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now this is the way I'm trying to write:
try {
BufferedWriter file=new BufferedWriter(new FileWriter(pathToNonEncryptedTxt+filename, true));
//FileWriter file = new FileWriter(pathToNonEncryptedTxt+filename);
file.write(userDigitalContent.toString(2));
file.newLine();
file.write(userFingerPrint.toString(2));
file.flush();
file.close();
} catch (IOException e) {
Log.v(TAG, "Error saving JSON into "+filename);
e.printStackTrace();
} catch (JSONException e) {
Log.v(TAG, "Error saving JSON into "+filename);
e.printStackTrace();
}
Oh!! BTW, I need to output something like that into a .txt File:
{
"userFingerPrint": {
"fingerPrint": {
"fingerPrint": "fingerPrintValue"
},
"fingerPrintMaterial": {
"methodType": "methodTypeValue",
"keySize": "5"
}
}
I guess there is some thing wrong in creating JSONObject in your code. Refer this tutorial for creating JSONObject once you create JSONObject you can get Sting from JSONObject by calling jsonObj.toString() and write that string to file

JSON-SIMPLE Can't cast to object to read through array

I'm trying to use JSON-Simple to read a configuration file that's in JSON using the following code
File f = new File("config.json");
JSONParser parser = new JSONParser();
try {
int i;
StringBuilder out = new StringBuilder();
FileReader reader = new FileReader(f);
while ((i = reader.read()) != -1) {
out.append((char) i);
}
JSONArray array = (JSONArray) JSONValue.parse(out.toString());
} catch (Exception e) {
System.out.println(e.toString());
}
or
File f = new File("config.json");
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(f));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("module");
Iterator<String> itreator = array.iterator();
while (itreator.hasNext()) {
System.out.println(itreator.next());
}
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but both are returning the error
org.json.simple.JSONObject cannot be cast to org.json.simple.JSONArray
however when doing
File f = new File("config.json");
try {
System.out.println(JSONValue.parse(new FileReader(f)));
} catch (Exception e) {
System.out.println(e.toString());
}
it returns the file's contents.
The config file can be seen here:
http://pastebin.com/5xJTHSwj
module tag in your config file isn't array. JSON array starts with [
e.g.
"module" : [{prop : "One"},{prop : "Two"}]
Use this code instead
JSONObject moduleObject= (JSONObject ) jsonObject.get("module");

Access JSON object in java

I need to update a value in my JSON file using java but somehow I am unable to.Following is my JSON format which I am trying to parse
{
"recentActivities":[
{
"displayValue":"POC | Augmented Reality",
"link":"poc.jsp?search=augmented%20reality",
"timestamp":"18/07/2013 17:33"
},
{
"displayValue":"POC | Image Editing in Hybrid Application",
"link":"poc.jsp?search=image%20editing",
"timestamp":"18/07/2013 01:00"
}
],
"lastEmailSent": "29/06/2013 00:00"
}
I need to update lastEmailSent to current date but somehow I am getting stuck. Below is my java code which i am using
private void updateLastEmailTimeStamp(String jsonFilePath) {
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
JSONObject lastEmailTimeStamp = new JSONObject();
FileReader reader =null;
try {
File jsonFile = new File(jsonFilePath);
reader = new FileReader(jsonFile);
jsonObject = (JSONObject) parser.parse(reader);
lastEmailTimeStamp = (JSONObject) jsonObject.get("lastEmailSent");
//write current date as last mail sent time.
writeTimeStamp(lastEmailTimeStamp, jsonFile);
APP_LOGGER.info("last Email Sent timestamp updated");
} catch (IOException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
} catch (ParseException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
private void writeTimeStamp(JSONObject lastEmailTimeStamp, File jsonFile) {
FileWriter writer = null;
try{
writer = new FileWriter(jsonFile);
String currentDate = MyDateFormatterUtility.formatDate(new Date(),"dd/MM/yyyy HH:mm");
lastEmailTimeStamp.put(SubscriptionConstants.LAST_EMAIL_TIMESTAMP, currentDate);
writer.write(lastEmailTimeStamp.toJSONString());
}catch(IOException ex){
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
}finally{
try {
writer.flush();
writer.close();
} catch (IOException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
}
I am getting error in the following line
lastEmailTimeStamp = (JSONObject) jsonObject.get("lastEmailSent");.
I guess I am not correctly parsing or accessing the object. Can somebody please make me correct?
Thank you!
I agree with #Hot Licks, but you can try fixing it by doing:
String lastEmailSent = jsonObject.getString("lastEmailSent");
Also, if that isn't the problem, it may be that the text coming from your file is not exactly the JSON text you posted here. In which case, you can read the file into a string, add a breakpoint and check the string to see if it has all the JSON elements you expect it to.
In Java 7 you can read the text in like:
String content = readFile(jsonFilePath, Charset.defaultCharset());
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
Finally, i was able to figure out the solution. Following changes were needed in the code
private void updateLastEmailTimeStamp(String jsonFilePath) {
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
FileReader reader =null;
try {
File jsonFile = new File(jsonFilePath);
reader = new FileReader(jsonFile);
jsonObject = (JSONObject) parser.parse(reader);
jsonObject.remove("lastEmailSent");
//write current date as last mail sent time.
writeTimeStamp(jsonObject, jsonFile);
APP_LOGGER.info("last Email Sent timestamp updated");
} catch (IOException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
} catch (ParseException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
} catch (RuntimeException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
/**
* Method to write current date as last mail sent timestamp
* denoting when the newsletter was sent last.
*
* #param jsonObj- date for last email sent.
* #param jsonFile - recentactivities.json file
*/
#SuppressWarnings("unchecked")
private void writeTimeStamp(JSONObject jsonObj, File jsonFile) {
FileWriter writer = null;
try {
writer = new FileWriter(jsonFile);
String currentDate = MyDateFormatter.formatDate(new Date(),"dd/MM/yyyy HH:mm");
jsonObj.put("lastEmailSent", currentDate);
writer.write(jsonObj.toJSONString());
}catch(IOException ex){
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
}finally{
try {
writer.flush();
writer.close();
} catch (IOException ex) {
APP_LOGGER.error(ex.getLocalizedMessage(), ex);
}
}
}

Categories

Resources