Object Sereialization, JAVA, Javascript - java

I have n object whose properties are being sent to a front end using REST protocols. There the object is taken in as an XML file and then parsed to JSON using JSON.parser. Now my target is to save this JSON file for some specified time on the disk. I tried serializing the object and storing it but it gets stored in binary/hex format. I need it to be in xml or JSON format.
Can anybody help me with this ?
Front-end is in JavaScript and the back-end is in Java.

Why you need to save JSON file on client side disk, it is not recommended practice. Rather you should use HTML5 web storage.

are you using JSON.simple? if so, there are several examples on their page for converting a string to json and back. in this case you already have a deserialized object so you would just need to serialize it to a string see https://code.google.com/p/json-simple/wiki/DecodingExamples
if you have your json object as a map you can
String jsonString = JSONValue.toJSONString(json);
or if it is already a JSONObject then simply
String jsonString = json.toJSONString();
then write the jsonString to your .json file.
FileWriter file = new FileWriter("/path/to/file.json");
file.write(jsonString);
file.flush();
file.close();
apologies if that is not the library you are using.

Related

Best way to send a JSon object from Servlet

The question can seem simple, but I didn't find a good answer yet. I need to send a JSon structure (build with an unspecified libretry I'm currently developing) from a Servlet to a remote page.
I'm interested in the best way to send the structure.
I mean, in my Servlet, inside the doPost() event, how should I manage the send?
I was thinking about 2 scenarios:
try (PrintWriter out = response.getWriter()) {
out.print(myJSon.toString(); // <- recursive function that overrides
// toString() and returns the entire JSon
// structure
} (...)
or
try (OutputStream os = response.getOutputStream()) {
myJSon.write(os, StandardCharsets.UTF8); // <- function that
// recursively writes chunk of my JSon structure
// in a BufferWriter created inside the root write function
// forcing UTF-8 encoding
} (...)
Or something different, if there's a better approch.
Note that the JSon structure contains an array of objects with long text fields (descriptions with more than 1000 characterd), so it can be quite memory consuming.
For why I'm not using standard JSon libreries, it's because I don't know them and I don't know if I can trust them yet. And also I don't know if I will be able to install them on the production server.
Thanks for your answers.
From your question i see multiple points to adress:
How to send your JSon
What JSon library can you use
How to use the library in production
How to send your JSon
From your code this seems to be an HTTP response rather than a POST on your Servlet so you need to know how to send a JSON string as an HTTP response's body
Do you use a framework for your web server or are you handling everything manually ? If you use a framework it usually does it for you, just pass the JSON String
If your doing it manually:
try (PrintWriter pw = response.getWriter()) {
pw.write(myJson.toString());
}
or
try (OutputStream os = response.getOutputStream()) {
os.write(myJson.toString().getBytes());
}
Both are valid, see Writer or OutputStream?
Your JSON's size shouldn't matter given what your saying, it's just text so it won't be big enough to matter.
What libraries can you use
There are a lot of JSON libraries for Java, mainly:
Jackson
GSon
json-io
Genson
Go for the one you prefer, there will be extensive documentation and resources all over google
How to use in production
If you are not sure you are able to install dependencies on the production server, you can always create an uber-jar (See #Premraj' answer)
Basically, you bundle the dependency in your Jar
Using Gson is good way to send json
Gson gson = new Gson();
String jsonData = gson.toJson(student);
PrintWriter out = response.getWriter();
try {
out.println(jsonData);
} finally {
out.close();
}
for detail json response from servlet in java

Convert one json format to another in java

I am looking for a utility which converts one json format to another by respecting at the conversion definitions from a preferably xml file. Is there any library doing something like this in java ?
For example source json is:
{"name":"aa","surname":"bb","accounts":[{"accountid":10,"balance":100}]}
target json is :
{"owner":"aa-bb","accounts":[{"accountid":10,"balance":100}]}
sample config xml :
t.owner = s.name.concat("-").concat(surname)
t.accounts = t.accounts
Ps:Please dont post solutions for this example, it is just for giving an idea, there will be quite different scenarios in mapping.
Is this what u need?
Open input file.
Read / parse JSON from file using a JSON library.
Convert in-memory data structure to new structure.
Open output file
Unparse in-memory data structure to file using JSON library.

Convert RSS feed to JSON in java

Is there any api or something to convert RSS feed to Json?
I used the api rss2json api with restTemplate, it's working fine when you map it with an entity but this one doesn't support multiple requests as it's gets overloaded plus there is no documentation for it or support so if the api goes down so is my app and I couldn't find something similar besides the rome plugin that converts to an object. I want direct conversion to Json.
I'm not sure what you mean by direct conversion to JSON, but you could simply use org.json to convert XML String to JSON String:
String xml = ..
JSONObject jObject = XML.toJSONObject(xml);
String json = jObject.toString();
More discussion here: Converting xml to json using jackson
I finished by using Rome plugin and built my own JSon structure step by step. no better solution so far.

How to convert an java serialized file to json file

I have a java class already serialized and stored as .ser format file but i want to get this converted in json file (.json format) , this is because serialization seems to be inefficient in terms of appending in direct manner, and further cause corruption of file due streamcorruption errors. Is there a possible efficient way to convert this java serialized file to json format.
You can read the .ser file as an InputStream and map the object received with key/value using Gson and write to .json file
InputStream ins = new ObjectInputStream(new FileInputStream("c:\\student.ser"));
Student student = (Student) ins.readObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(student );
try {
//write converted json data to a file named "file.json"
FileWriter writer = new FileWriter("c:\\file.json");
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
There is no standard way to do it in Java and also there is no silver bullet - there are a lot of libraries for this. I prefer jackson https://github.com/FasterXML/jackson
ObjectMapper mapper = new ObjectMapper();
// object == ??? read from *.ser
String s = mapper.writeValueAsString(object);
You can see the list of libraries for JSON serialization/deserialization (for java and not only for java) here http://json.org/
this is because serialization seems to be inefficient in terms of appending in direct manner
Not sure if JSON is the answer for you. Could you share with us some examples of data and what manipulations you do with it?
You can try Google Protocol Buffers as alternative to Java serialization and JSON.
In my answer in topic bellow there is an overview of what GPB is and how to use, so you may check that and see if it suits you:
How to write/read binary files that represent objects?

Write json to text file, jettison

I have created a JSONOBject JSONObject features = new JSONObject(); which I want to store it in a txt file. I am using Jettison LIbrary for handling json files. However I didn't find a way to write json to file. Any idea?
You can use Json Writer to create a text which can be stored in a file.
The text generated here abides all of the syntax rules of JSON and allows you to save the JSON object as text file.

Categories