trying to write nested JSON into File - java

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

Related

How to convert a string to JSON?

I'm using volley to get a file from the internet, the file is an array. I'm saving the file in cache to do this I have to convert the file into a string. I have a function that reads the cache and pass the response to another file to display
the information, but when i'm trying to convert the resoionse back to an array i get an error
Value AuthStatus of type java.lang.String cannot be converted to JSONObject
I'm really new on android, hoping someone can point me on the right direction
private void cacheFile(JSONObject response) {
JSONObject res = response;
String filename = "jsonfile";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(res.toString().getBytes("utf-8"));
outputStream.close();
Log.e(TAG, "Bien");
} catch (Exception e) {
e.printStackTrace();
}
}
private void readCache(String filename) {
FileInputStream inputStream;
try {
inputStream = openFileInput(filename);
inputStream.read();
String body = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());
inputStream.close();
fromCache(body);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fromCache(String json) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("cars");
Log.e(TAG, "Array Size: " + jsonArray.length());
} catch (JSONException e) {
e.printStackTrace();
}
}
You have to use JSONValue.parse method as shown below:
public void fromCache(String json) {
JSONObject jsonObject = null;
try {
jsonObject = (JSONObject)JSONValue.parse(json);
JSONArray jsonArray = jsonObject.getJSONArray("cars");
Log.e(TAG, "Array Size: " + jsonArray.length());
} catch (JSONException e) {
e.printStackTrace();
}
}

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

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.

Is there a way to parse JSON with java? [duplicate]

This question already has answers here:
Converting JSON data to Java object
(14 answers)
Closed 6 years ago.
Here is what I have so far:
public Bitmap getAlbumCover(Context context, String song, String artist) {
this.context = context;
song = song.replace(" ", "%20");
artist = artist.replace(" ", "%20");
try {
conn = new URL("https://api.spotify.com/v1/search?q=track" + song + ":%20artist:" + artist + "&type=track)").openConnection();
} catch (IOException e) {
e.printStackTrace();
}
if (conn != null)
conn.setDoOutput(true);
try {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
if (reader != null) {
// Read Server Response
String line2 = null;
try {
while ((line2 = reader.readLine()) != null) {
sb.append(line2);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
json = new JSONArray(sb.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONParser parser= new JSONParser();
try {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
try {
array = (JSONArray) jsonObject.get("items");
} catch (JSONException e) {
e.printStackTrace();
}
// take each value from the json array separately
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
The JSON I am using is located here:
https://api.spotify.com/v1/search?q=track:Ready%20To%20Fall%20artist:rise%20against%20&type=track
I am trying to get the image url located in the images array and the preview_track url located in items.
I use Jackson library to parse JSON to java opbject.
if you create your java object with the same structure as JSON this can be done using this:
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonUrl, YourClass.class);
So your OBJECT will have tracks and then tracks will have object album and album will have object other details. Just structure it as the JSON is and you are there.

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