Write json to text file, jettison - java

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.

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 convert XML to JSON in Java excluding some tags?

I want to convert XML to JSON in Java but most of the answers focus on converting all tags in XML to JSON. But my requirement is to skip some of the tags and convert remaining tags to JSON. Any help would be appreciable.
I have tried XML.toJSONObject(String); method from the org.json package but it does not suggest any way to skip some tags.
if you are using gson simply using remove api in JsonObject under com.google.gson
lets suppose we have test attribute in your model that you do not want to display,
JsonObject jsonObj;
jsonObj.remove("test");
You will be having the json object without test attribute.

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.

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);

Categories