How to convert an java serialized file to json file - java

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?

Related

Writing a JSON string from Java to Excel in a formatted way

I am trying to write a JSON in string format to an excel file in Java. I know how to write to the file but I can't figure out how to format it.
For example if I wanted to write this:
{'data':[{'id':1,'name':'Eredivisie','active':true}]}
To an excel file how could I implement it so each value appears in its own separate cell? Like this: Screenshot of sample excel sheet
I have done research but can't find a simple answer. Any help would be appreciated, thanks.
The CSV (comma separated values) file format is a good choice.
So you would just output text to a file, separating each value with a comma. E.G:
ID,Name,Active
1,Eredivisie,true
...etc
Depending on your data (if it contains any commas), you may have to choose a different character to separate the values. Good job that in excel you can specify which character you are using.
Just parse the JSON as simple POJO object and then format the POJO object as string to create a CSV format.
The code will look some thing like this:
ObjectMapper mapper = new ObjectMapper();
List<Data> dataList = mapper.readValue(json, List.class);
StringBuilder csvFormattedText = new StringBuilder("id, name, active");
forEach (Data data : dataList) {
scvFormattedText.append(data.getId()).append(", ")
.append(data.getName)
.append(", ")
.append(data.getActiveStatus())
.append("\n");
}
File csvFile = new File("fromJSON.csv");
try ( PrintWriter write = new PrintWriter(csvFile)) {
out.println(csvFormattedText.toString());
}
Here Data is the POJO class which is created based on the fields in JSON.
In this way, you can convert the JSON to CSV file and thus it can be opened using excel.
If you dont like this approach, you may have to use libraries like Apache POI to convert JSON to xls. You have to follow same process, only difference it POI help you to set the values in each cell of the spreadsheet.
Further reading on POI library: Apache POI
Hope it helps.
you don't need to do something more just pull the json and then apply them to write in excel ,create new row then create new 4 cells in each object
JSONObject json=new JSONObject("{\"data\":[{\"id\":1,\"name\":\"Eredivisie\",\"active\":true}]}
JSONObject data=new json.getJSONObject("data"));
cell1.setCellStringValue(data.getString("id"));
cell2.setCellStringValue(data.getString("name"));
cell3.setCellStringValue(data.getString("Eredivisie"));
cell4.setCellStringValue(data.getString("active"));

How to get a string out of (libgdx) json

I really wonder how this would be done properly(*):
FileHandle file = Gdx.files.local("test.json");
Json json = new Json(JsonWriter.OutputType.json);
JsonWriter writer = new JsonWriter(new StringWriter());
json.setWriter(writer);
json.writeObjectStart();
json.writeValue("name", "Testing");
json.writeObjectEnd();
file.writeString(..., false); // Here I am stuck
As you can see I want to manually (!) create a json object and write just one string in there. I do not want to use a serializer or anything the like for this matter.
In https://github.com/libgdx/libgdx/wiki/Reading-&-writing-JSON there is a passage: Serialization Methods
In there the same is done. But how can I translate my Json to a String that can be written to a file? toString() is doing no good here.
(*) Once again, I want to emphasize I do NOT want to use a serializer in that case but build my own json-file from scratch. I'm totally aware of the problems and unmanagable-code this could lead to. Thank you!

Object Sereialization, JAVA, Javascript

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.

Editing a .json file: adding lines in certain parts of the file?

I am trying to edit a ".json" file using code or scripts to attach to an installer.
I need it to add in a few lines into a .json config file but I have not found any code or online tutorials on how to do this.
I tried searching for ways to add lines to a normal .txt file but no luck on that either.
What I have found online is appending, but that's not what I need.
Maybe a way to search for certain point of the file to move the pointer to then add in the lines?
I know a little Java but no other coding language.
Is there a way to do it in Java or some small scripts?
Yes, there is a way. Here is some pseudo-code to give you the concept.
JSONObject json = fileRead("myfile.json")
JSONObject objToAdd = new JSONObject();
json.add(objToAdd);
fileWrite(json);
If you use Java 7 and your Json is not huge, this is a easy way to add lines:
List<String> lines = Files.readAllLines(Paths.get("C:\\Automation1\\some.json"), StandardCharsets.UTF_8);
lines.add(6, "{ \"abc\": 123}"); // as example add data to row 6
Files.write(Paths.get("C:\\Automation1\\some.json"), lines, StandardCharsets.UTF_8);
But this technique is hard to maintain.
I suggest you to convert Json to Object, and convert it back to Json file after you adit the Object
Use a json parser library such as json-simple. First read the content, pass it to the parser and create a Json Object. Here is an example:
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
StringWriter out = new StringWriter();
obj.writeJSONString(out); // your writer object, i.e., FileWriter
String jsonText = out.toString();
System.out.print(jsonText);
Well you can also add one JsonObject to another: jsonObj1.add(jsonObj);

Java XStream with HashMap

I want to use XStream to convert a java hash to a json hash. I feel like this should be easier than it seems. What I'm looking for is a way to make:
Map<String, String> map = new HashMap<String, String>();
map.put("first", "value1");
map.put("second", "value2");
become
{'first' : 'value1', 'second' : 'value2' }
The closes I have converts it into a series of arrays.
XStream xstream = new XStream(new JettisonMappedXmlDriver() {
public HierarchicalStreamWriter createWriter(Writer writer) {
return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
}
});
xstream.toXML(map);
which becomes
[["first", "value1"], ["second", "value2"]]
I feel like converting a java hash to json hash should be straight forward. Am I missing something?
The thing is that XStream is first and foremost designed to marshal and unmarshal Java objects to XML, JSON being just an afterthought, it most certainly has the least elegant support.
The technical problem being that as XStream must support both - XML and JSON formats, JSON map representation suffers, as there is no native way to represent a map-like structures in XML.
You can try to use the "official" json lib for java from json.org.
Calling:
JSONObject jsobj = new JSONObject(map);
String strJson = jsobj.toString();
I had similar issues when converting to jSon. My solution to this problem was to have the string already formatted to JSon before dropping into the file (in my case a database). The most efficient process I have come up with so far was to create a toJson function inside my classes to work just like toString.
Example:
Converts the objects data output string into Json format
public JsonObject toJson()
{
JsonObject temp = new JsonObject();
temp.addProperty(tagName,floatData);
return temp;
}
So for you, implement a similar process while populating your map.

Categories