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);
}
}
}
Related
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();
}
}
I want to write to a file from a Map object. Here is my attempt.
try {
stuMap.put(student.getId(), student);
Path file = Paths.get("student.txt"); // to create the file
Files.write(file, stuMap, Charset.forName("UTF-8")); // try to save in the file
/* fileReaderWriter.createFileIn_NIO(stuMap);*/
try {
fileReaderWriter.createFileIn_NIO(stuMap);
} catch (IOException ex) {
System.out.println("file not saved");
}
return true;
} catch (Exception ex) {
System.out.println("not stored in Map");
return false;
}
How do I make this work?
You can use tools like Jackson to write java maps out as json and read it in as map. As others have mentioned, this is only one possible way.
Full working Read/Write Example
#Test
public void loadMapFromFileAndSaveIt(){
Map<Object, Object> map = loadMap("map.json");
map.put("8", "8th");
map.remove("7");
save(map,"/path/to/map2.txt");
}
private Map<Object, Object> loadMap(String string) {
ObjectMapper mapper = new ObjectMapper();
try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("map.json")) {
return mapper.readValue(in, HashMap.class);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
private void save(Map<Object, Object> map,String path) {
try (PrintWriter out = new PrintWriter(path)) {
out.println(toString(map));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public String toString(Object obj) {
try (StringWriter w = new StringWriter();) {
new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
return w.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
If the file map.json on your classpath contains
{
"1":"1th",
"2":"2th",
"3":"3th",
"4":"4th",
"5":"5th",
"6":"6th",
"7":"7th"
}
The code above will modify it and write it to a file /path/to/map2.txt that will contain
{
"1" : "1th",
"2" : "2th",
"3" : "3th",
"4" : "4th",
"5" : "5th",
"6" : "6th",
"8" : "8th"
}
There is concept in java for saving state of object and retrieve it back later called 'Serialization'.
To Write Object
File fileToSaveObject=new File("path");
Object objectToSave=new Object();
FileOutputStream fileOut = new FileOutputStream(fileToSaveObject);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(objectToSave); // It will save 'objectToSave' in given file
out.close();
fileOut.close();
To Read Object
File fileToReadObject=new File("path");
Object objectToRead;
FileInputStream fileIn = new FileInputStream(fileToReadObject);
ObjectInputStream in = new ObjectInputStream(fileIn);
objectToRead= (Object) in.readObject(); // It will return you the saved object
in.close();
fileIn.close();
Just use org.apache.commons.io.FileUtils
import org.apache.commons.io.FileUtils;
yourMap.forEach((key, value) -> {
FileUtils.writeStringToFile(
outputFile, key + ", " + value + "\n", true);
});
A simple variant to solve the problem is to use Gson library:
String str = new Gson().toJson(yourMap);
File file = new File(fileName);
try(FileOutputStream stream = new FileOutputStream(file)) {
file.createNewFile();
stream.write(str.getBytes());
}catch (IOException e){
System.out.println("can't write to file");
}
I know I'm not doing something correctly. I know the file needs to be Serializable to read a text file.
I've got implements Serializable on the main class. But my readText and my writeText aren't converting.
Nothing is coming in when I read and when I write out the file is not text.
public static ArrayList<String> readText() {
ArrayList<String> read = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Reading serialized file",
FileDialog.LOAD);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File inFile = new File(dirPath + foName);
BufferedReader in = null;
ObjectInputStream OIS = null;
try {
in = new BufferedReader(new FileReader(inFile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
line = in.readLine();
} catch (IOException e1) {
e1.printStackTrace();
while (line != null) {
try {
FileInputStream IS = new FileInputStream(inFile);
OIS = new ObjectInputStream(IS);
inFile = (File) OIS.readObject();
} catch (IOException io) {
io.printStackTrace();
System.out.println("An IO Exception occurred");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace(); // great for debugging!
System.out.println("An IO Exception occurred");
} finally
{
try {
OIS.close();
} catch (Exception e) {
}
}
}
}
return read;
}
public static void writeText(ArrayList<String> file) {
ArrayList<String> write = new ArrayList<String>();
Frame f = new Frame();
FileDialog foBox = new FileDialog(f, "Saving customer file",
FileDialog.SAVE);
foBox.setVisible(true);
String foName = foBox.getFile();
String dirPath = foBox.getDirectory();
File outFile = new File(dirPath + foName);
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(outFile)));
for (int i = 0; i < write.size(); i++) {
String w = write.get(i);
out.println(file.toString());
}
}
catch (IOException io) {
System.out.println("An IO Exception occurred");
io.printStackTrace();
} finally {
try {
out.close();
} catch (Exception e) {
}
}
}
Nothing is coming in
You're never calling read.add(line) and you're attempting to read the file within an infinite loop inside of the catch block, which is only entered if you are not able to read the file.
Just use one try block, meaning try to open and read the file at once, otherwise, there's no reason to continue trying to read the file if it's not able to be opened
List<String> read = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(inFile)) {
String line = null;
while ((line = in.readLine()) != null) {
read.add(line); // need this
}
} catch (Exception e) {
e.printStackTrace();
}
return read;
Now, whatever you're doing with this serialized object stuff, that's completely separate, and it isn't the file or your main class that needs set to Serializable, it's whatever object you would have used a writeObject method on. However, you're reading and writing String objects, which are already Serializable.
when I write out the file is not text
Not sure what you mean by not text, but if you followed the above code, you'll get exactly what was in the initial file... Anyway, you do not need a write list variable.
You must use the individual lines of ArrayList<String> file parameter instead, but not file.toString()
for (String line:file) {
out.println(line);
}
out.close(); // always close your files and writers
I am trying to extract values from JSON from the URL provided below using GSON java library:
http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json
I have successfully used the code provided below to extract data from URL below:
http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json
Code:
String url = "http://api.wunderground.com/api/b28d047ca410515a/conditions/q/-33.912,151.013.json";
String url2 = "http://api.wunderground.com/api/b28d047ca410515a/forecast/q/-33.912,151.013.json";
InputStream is = null;
try {
is = new URL(url).openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JsonElement je = new JsonParser().parse(jsonText);
System.out.println("Current Temperature:" + getAtPath(je, "current_observation/temp_c").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
However I am getting exception trying to extract from url2 as per code below , it seems to be a more complicated json to get values from, any help please?
// below code not working
weather_icon_url = getAtPath(je, "current_observation/icon_url").getAsString();
is = new URL(url2).openStream();
BufferedReader rd2 = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText2 = readAll(rd2);
JsonElement je2 = new JsonParser().parse(jsonText2);
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
getAtPath code:
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
current = current.getAsJsonObject().get(ss[i]);
}
return current;
}
The problem you are facing is because there is an issue with the getAtPath implementation.
[{"date":{"epoch":"1459152000"... represents a JSONArray which the method is trying to access as JSONObject. Hence the IllegalStateException.
JsonObject com.google.gson.JsonElement.getAsJsonObject()
convenience method to get this element as a JsonObject. If the element
is of some other type, a IllegalStateException will result. Hence it
is best to use this method after ensuring that this element is of the
desired type by calling isJsonObject() first.
You can update and use something like below, as of now it returns only the first element.
private static JsonElement getAtPath(JsonElement e, String path) {
JsonElement current = e;
String ss[] = path.split("/");
for (int i = 0; i < ss.length; i++) {
if(current instanceof JsonObject){
current = current.getAsJsonObject().get(ss[i]);
} else if(current instanceof JsonArray){
JsonElement jsonElement = current.getAsJsonArray().get(0);
current = jsonElement.getAsJsonObject().get(ss[i]);
}
}
return current;
}
This should work:
System.out.println("max Temperature:" + getAtPath(je2, "forecast/simpleforecast/forecastday/high/celsius").getAsString() );
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.