2

I want to save a Java class named MyClass into a text file and I want to use JSON to encode the class for file writing purposes instead of implementing the Serializable interface. Moreover, to save the class I want to use the Google's Gson library and in particular the JsonWriter class. The MyClass class is, for instance, defined as follows:

public class MyClass{
 String html;    
 public MyClass(){}
}

As shown in the example above, MyClass has a String field named html, that obviously must contain HTML code.

Can I save the class into a text file by using JSON via the JsonWriter or I should encode or do something similar with the html field (e.g. a call to an URLEncode-like function) before to give it to JsonWriter?

10
  • What happened when you tried to serialize it ? Commented Apr 13, 2013 at 17:15
  • I don't wan't to serialize the class because after I save it I need to use it in a non-Java application. Commented Apr 13, 2013 at 17:17
  • Looks like you can, but is that really a good design? Commented Apr 13, 2013 at 17:17
  • @LuiggiMendoza I need to import the class data into another program then. Is there any better way to save the file without using Java serialization? Commented Apr 13, 2013 at 17:19
  • What have you tried to accomplish it? Asking can I do this without even trying myself? is not an option here. Commented Apr 13, 2013 at 17:22

1 Answer 1

2

Since escaping new lines / quotes etc can make this a little tricky, why not just use XStream to convert the object to XML and wrap the HTML in a CDATA section ? Json has no equivalent for a CDATA section.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.