I was trying to persist a complex object in java and re-use it later after re-running the program. Java supports traditional Serializable interface which is also cool. But it was rather looking for a better way to do it and I found this awesone API called json-io. You could also download the jar file from its maven repository, include it in the classpath and use it. I am writing a simple code to demonstrate it for my reference but you could always go to its site and learn more.
Well, I should mention this. I was trying to implement a desktop application which has some settings. The application should save its settings and perform according to them. The settings should persist, the next time the application is started. I could simply create a map, for the options, update the maps in run time and save them in a file on exit and reload from the same file.
Well, I should mention this. I was trying to implement a desktop application which has some settings. The application should save its settings and perform according to them. The settings should persist, the next time the application is started. I could simply create a map, for the options, update the maps in run time and save them in a file on exit and reload from the same file.
import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Rajan Prasad Upadhyay
*/
public class Dog {
Barks bark = new Barks();
String name ;
public Barks getBark() {
return bark;
}
public void setBark(Barks bark) {
this.bark = bark;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
String json = "";
try {
Dog dog = new Dog();
dog.setName("Tommy");
json = JsonWriter.objectToJson(dog);
System.out.println(json);
} catch (IOException ex) {
Logger.getLogger(Dog.class.getName()).log(Level.SEVERE, null, ex);
}
try{
String sjon = json;
Dog dg = (Dog) JsonReader.jsonToJava(sjon);
System.out.println(dg.getName() + " sounds like "+ dg.getBark().getSound());
}catch (Exception ex) {
Logger.getLogger(Dog.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Barks{
String sound = "woo woo";
public String getSound() {
return sound;
}
public void setSound(String sound) {
this.sound = sound;
}
}
No comments:
Post a Comment
If you like to say anything (good/bad), Please do not hesitate...