Library to create JSON file from parsed text document - java

I parsed a timetable from a text document and reached the step where I have to create a JSON file from the raw data like in the sample below. Is there any library which could help me create a JSON formatted file from a raw text document?
I appreciate any help.
Sample how it could look like:
{"route": 1
"info": [
{"direction": "Surrey Quays"},
{"stops": [{"stops_name": "Lancaster Place"},
{"arrival_time":{
"mon-fri": ["04:41", "05:41", "06:09"],
"sat": [ "05:38", "06:07","06:37"]
}
}
]
}
Some sample from the text document
Surrey Quays
1
Lancaster Place
mon-fri 04:41 05:41 06:09
sat 04:41 05:41 06:09
Edit:
for (Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> timeEntries = entry.getValue();
JSONObject timeTable = new JSONObject();
timeTable.put("route", route);
JSONObject info = new JSONObject();
info.put("direction", direction);
JSONObject stops = new JSONObject();
stops.put("stops_name", key);
JSONObject arrivals = new JSONObject();
JSONArray arrivalMoFr = new JSONArray();
JSONArray someArray = new JSONArray(timeEntries);
arrivalMoFr.put( someArray);
arrivals.put("mon-fri", arrivalMoFr);
stops.put("arrival_time", arrivals);
info.put("stops", stops);
timeTable.put("info", info);
System.out.println(timeTable.toString(3));
}
**Some of the result **
"arrival_time": {"mon-fri": [[
"05:04",
"05:39",
"19:11",
"19:41",
"20:11"
]]},

You could use this JSON library from json.org . But it is just one example of all the libraries out there.
This is how you could use it:
Let's say you already have your parser (meaning you already have a method that can read the text document and that knows what to do with the data)
JSONObject timeTable = new JSONObject(); // first create the "main" JSON Object
timeTable.put("route", 1); // this first entry is just a number
JSONObject info = new JSONObject(); // now you need a second JSON OBject to put all the info in
info.put("direction", "Surrey Quays"); // first info, the direction
JSONObject stops = new JSONObject(); // now you need another Object for all the stops and stop related info
stops.put("stops_name", "Tension Way"); // like the name for the stop
JSONObject arrivals = new JSONObject(); // now all the arrivals
JSONArray arrivalMoFr = new JSONArray(); // this is the first time where an array makes sense here
arrivalMoFr.put("05:38"); // arrival time 1
arrivalMoFr.put("06:07"); // arrival time 2
arrivalMoFr.put("06:37"); // ...
arrivals.put("mon-fri",arrivalMoFr); // add the arrival times array as mon-fri to the arraivals object, do the same with all other arrival times (Saturday, Sunday...)
stops.put("arrival_time", arrivals); // now add the arrival time object to your stops
info.put("stops", stops); // and put the stops to your info
timeTable.put("info", info); // once you added all your infos you can put the info into your timeTable
System.out.println(timeTable.toString(3)); // this is just for testing. The number 3 tells you how many whitespaces you want for text-identaion
And this is the output I am getting:
{
"route": 1,
"info": {
"stops": {
"arrival_time": {"mon-fri": [
"05:38",
"06:07",
"06:37"
]},
"stops_name": "Tension Way"
},
"direction": "Surrey Quays"
}
}
I realize this is not exactly the same as in your example. But I think you get the idea. Remember, the order of the elements in a JSON Object is irrelevant. When reading the JSON, the program will read it like json.get("stops_name"); and it does not care if the stops name are before or after the arrival times.
ADDITION
I saw that you put the "stops_name" and the "arrival_time"-array in separate JSON Objects. Well if you want to put them all in an object called "stops", which suggests, that you will list more than one stop, I suggest to put them together. Because the data in the JSON object has no particular order.
"stops": [
{
"stop_name" : "Lanvester Place",
"arrival" : {...}
},{
"stop_name" : "Some other Place",
"arrival" : {...}
}
...
]
To your EDIT:
your are getting double braces [[ because you are adding an array to your arrivals Object where the first entry is again an array.
so instead of doing this:
JSONArray arrivalMoFr = new JSONArray();
JSONArray someArray = new JSONArray(timeEntries);
arrivalMoFr.put( someArray);
arrivals.put("mon-fri", arrivalMoFr);
you should do this:
JSONArray arrivalMoFr = new JSONArray(timeEntries); // put your list of time entries directly into the arrivalMoFr array
arrivals.put("mon-fri", arrivalMoFr); // then add the arrivalMoFr array to the arrivals object

You need to parse the text file first. I sugest to create dedicated Java classes for your data. Make sure the classes reflect the structure of the desired JSON.
Once you have that you can feed youf Java object to a JSON library which turns it into JSON for free. I'm using GSON for that. I'm sure you will find some more candidates on SO or Google.

Related

JSON Input for POST request to call REST API

How do i convert a model Person to match the input?
Person p = new Person(name, age, amountInBank);
(name in String, age in int and amountInBank in double)
I want my JSON Input to be as follow:
{
"ID": "H123",
"list" : [
{
"name" : "ally",
"age": 18,
"amountInBank": 200.55
}
]
}
Currently my code to call REST API is:
JSONObject jsonInput= new JSONObject();
jsonInput.put("ID", "H123");
//put in list input in JSON -> HELP NEEDED
Resource resource = client.resource(URL HERE);
resource.contentType(MediaType.APPLICATION_JSON);
resource.accept(MediaType.APPLICATION_JSON);
ClientResponse cliResponse = resource.post(jsonInput);
Tried many ways but couldn't achieve the expected input for list in JSON format. Please help
Method 1:
ArrayList<Map<String, Object>> list = new ArrayList<>();
list.add(p);
jsonInput.put("list" , list);
Method 2:
JSONArray jsonArr = new JSONArray();
jsonArr.add(p);
jsonInput.put("list", jsonArr);
Method 3:
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "ally");
map.put("age", 18);
map.put("amountInBank" : 255.55);
jsonInput.put("list", map);
Safest bet is to use a well known library for the marshalling, such as Jackson. It is able to convert your object to JSON format with the following:
ObjectMapper mapper = new ObjectMapper(); //from Jackson library
Person p = new Person(name, age, amountInBank); //your POJO
String jsonString = mapper.writeValueAsString(p); //convert
Source: https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
There are also other alternatives, this is just a personal preference as Jackson is very widely used and well documented.
If you're trying to get a list of array JSON objects then just substitute the Person object with List<Person> and try to marshall that.
Try the code below
val listJsonArry = JsonArray()
var jsonObject = JsonObject()
jsonObject.add("name", "ally")
jsonObject.add("age", "18")
jsonObject.add("amountInBank", "200.55")
listJsonArry.add(jsonObject)
PostData
var postjsonObject = JsonObject()
postjsonObject.add("ID", "H123")
postjsonObject.add("list", listJsonArry)
First you have to create JSONObject and put ID, H123.
Then you have to create Another JSONObject wich will accept a person details.
pass another JSONObject to JSONArray and path JSONArray to JSONObjct. check the code
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject(); // first json object
jsonObject.put("ID", "H123"); put ids.
JSONArray jsonArray = new JSONArray(); // prepear json array
Person person = new Person("Ally", 18, 200.55); // create person object and populate it with data
// JSONObject jsonObject = new JSONObject(person); you can pass your person directly to JSONObject constructor and it will deparse it base on your getter methods in person class.
JSONObject jsonObject1 = new JSONObject(); // then pass person data to Json object
jsonObject1.put("name", person.getName());
jsonObject1.put("age", person.getAge());
jsonObject1.put("amountInBank", person.getAmountInBank());
jsonArray.put(jsonObject1); // pass json object to json array
jsonObject.put("list", jsonArray); // and pass json array to json object
System.out.println();
try (FileWriter file = new FileWriter("person.json")) {
file.write(jsonObject.toString(5));
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
above code will produce output
{
"ID": "H123",
"list": [{
"name": "Ally",
"amountInBank": 200.55,
"age": 18
}]
}
if you need to do that from database, more like there will be a lot of persons. put person object and json object in some kind of loop and populate it as long as you want. then pass it to json array and json array to jsonobject to have many records.

Android - JSON - How do I create a JSON Object & JSON Array to match this format using JSONObject & JSONArray Types?

How do I create a JSON Object & JSON Array to match this format using JSONObject & JSONArray Types?
{"PeripheralList":
[{"Category":"BP","CollectionTime":"2015-12-28T09:09:22-05:00",
"DeviceInfo":null,
"Readings":[
[{"Name":"SYS","Type":"INT","Value":"200"},
{"Name":"DIA","Type":"INT","Value":"199"},
{"Name":"HTR","Type":"INT","Value":"102"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T08:12:53-05:00"}]
]},
{"Category":"HR","CollectionTime":"2015-12-28T09:09:22-05:00",
"DeviceInfo":[{"Name":"UNITS","Value":"Rate"}],
"Readings":[
[{"Name":"HR","Type":"DECIMAL","Value":"200.7"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T07:26:49-05:00"}],
[{"Name":"HR","Type":"DECIMAL","Value":"155.2"},
{"Name":"READINGTIME","Type":"DATETIME","Value":"2015-12-27T14:39:11-05:00"}]
]}
]}
Any help would be appreciated. Thanks.
You should be able to pass the JSON string directly to the constructor.
JSONObject mainObject = new JSONObject(jsonString);
Below should give you an idea of how it works when you want to manually create a JSON Object.
JSONObject mainObject = new JSONObject(); // Main Object.
JSONArray categoryArray; // Category Array.
JSONObject categoryObject; // Category Object.
JSONArray readingsMainArray; // An array of arrays.
JSONArray readingsChildArray; // A child array.
JSONObject readingsObject; // A readings entry.
// Create arrays.
readingsMainArray = new JSONArray();
readingsChildArray = new JSONArray();
// Create JSONObject.
readingsObject = new JSONObject();
// Put values.
readingsObject.put("Name":"SYS");
readingsObject.put("Type":"INT");
readingsObject.put("Value":"200");
// Add to the child array.
readingsChildArray.put(readingsObject);
// Repeat 3 times for the other values.
// Now add the readings child array to the main array.
readingsMainArray.put(readingsChildArray);
// Now the category JSONObject.
categoryObject = new JSONObject();
// Put values.
categoryObject.put("Category","BP);
categoryObject.put("CollectionTime","2015-12-28T09:09:22-05:00");
categoryObject.put("DeviceInfo",null);
categoryObject.put("Readings", readingsMainArray);
// Put the category object into the category array.
categoryArray = new JSONArray();
categoryArray.put(categoryObject);
// Repeat this process for the "second" category array.
// Add category array to the main object.
mainObject.put("PeripheralList",categoryArray);
Let me know if this helps.

Parsing multiple json objects in java

I have this json file that I'm trying to parse in my program.
{
"items": [{
"0": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
},
"1": {
"item_name":"Test Item",
"item_rarity":2,
"item_material":"STICK",
"required_level":1,
"min_damage":100.0,
"max_damage":200.0,
"item_set":"The cool kids",
"attributes":[{"name":"lifesteal","modifier":20}]
}
}]
}
I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.
Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
JSONObject jsonObject = (JSONObject) obj;
JSONArray items = (JSONArray) jsonObject.get("items");
for (int i = 0; i < items.size(); i++) {
JSONObject item = (JSONObject) items.get(i);
System.out.print(item.toString());
}
Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).
What did you find troubling with GSON?
If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.
Gson gson = new Gson();
JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);
Then you can call
JsonArray array = jsonFile.get("items").getAsJsonArray();
Then to grab the attributes from the first element of the array.
array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

Parse JSONObject and JSONArray and fix them in the listview

How to parse JSONArray inside JSONObject?. Here is the JSON response I'm getting from the server.
{
"searchdata": {
"titles": [
"<b>Laptop</b> - Wikipedia, the free encyclopedia",
"<b>laptop</b> - definition of <b>laptop</b> by the Free Online Dictionary ..."
],
"desc": [
"A <b>laptop</b> computer is a personal computer for mobile use. A <b>laptop</b> has most of the same components as a desktop computer, including a display, a keyboard, a ...",
"lap·top (l p t p) n. A portable computer small enough to use on one&apos;s lap. <b>laptop</b> [ˈlæpˌtɒp], <b>laptop</b> computer. n (Electronics & Computer Science / Computer ..."
],
"links": [
"http://en.wikipedia.org/wiki/Laptop",
"http://www.thefreedictionary.com/laptop"
],
"nextpage": ""
}
}
I'm able to get JSONObject but how to get JSONArray one by one, so that I can fix them in the listview.
I want to show the values of each array in a single row of the listview and so on....
Any help will be appreciated.
Very easy..
you need to fix code like this:
//jsonString is your whole JSONString which you have shown above
JSONObject jObj = new JSONObject(jsonString);
JSONObject jSearchData = jObj.getJSONObject("searchdata");
JSONArray jTitles = jSearchData.getJSONArray("titles");
JSONArray jDesc= jSearchData.getJSONArray("desc");
JSONArray jLinks= jSearchData.getJSONArray("links");
String nextPage = jSearchData.getString("nextpage");
//and so on and so forth
For fetching the array items and show it into a listview:
//you can iterate over each item and add it to an ArrayList like this:
//i am showing you a single one,follow the same process for other arrays:
ArrayList titlesArray = new ArrayList();
for (int i = 0; i < jTitles.length(); i++) {
String item = jTitles.getString(i);
titlesArray.add(item);
}
Next you make this arraylist a source to a listview like this:
// Get a handle to the list view
ListView lv = (ListView) findViewById(R.id.ListView01);
lv.setAdapter(new ArrayAdapter<string>((Your activity class).this,
android.R.layout.simple_list_item_1, titlesArray));
Consider that your top level JSON will be parsed into a JSONObject, and that subsequently you can request to receive from it, any sub level objects and/or arrays via the methods getJSONObject(name) and getJSONArray(name). Your arrays of interest are two levels deep in the JSON hierarchy, so you will need something like this:
String json = ...;
JSONObject rootObj = new JSONObject(json);
JSONObject searchObj = rootObj.getJSONObject("searchdata");
JSONArray titlesObj = searchObj.getJSONArray("titles");
JSONArray descsObj = searchObj.getJSONArray("desc");
JSONArray linksObj = searchObj.getJSONArray("links");
You can iterate any of the arrays as such (using titles as an example):
for(int i = 0; i < titlesObj.length(); i++) {
String title = titlesObj.getString(i);
}
it will be help:
JSONArray titles = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("titles");
JSONArray desc = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("desc");
JSONArray links = new jSONObject(jsonstring).getJSONObject("searchdata").getJSONArray("links");

Is JSON same with GSON?

I have tried to run following code
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();
JSONArray data = new JSONArray();
for (Object obj : result) {
JSONArray row = new JSONArray();
User user = (User) obj;
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();
The result from toString function for both jsonResponse are as follows:
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}
I would like to eliminate the " symbol before [ and after ] from the first json response just like the second one (I noticed that the " is added after the array being put to the jsonResponse object). How can I accomplish this ?
Since you first convert your "result" to a String, and then add it to aaData, it will end up quoted, like a String should. If all you'd like to do is to remove the quotes, you could do something like this in line 2:
String json = "##" + gson.toJson(result) + "##";
and this in line 8:
jsonResponse.toString().replace("\"##", "").replace("##\"","");
(of course you need to choose the "quote marker" ## such that it will never appear as actual string content in your data anywhere else)
But the cleaner solution (although probably slower) would likely be to convert your String to an actual JSONObject by changing line 2 to:
JSONObject json = new JSONObject(gson.toJson(result));

Categories

Resources