Java : JSONObject.put looped gives wrong order? - java

Today I started writing a simple parser for a log file. I want to take the log file and transform it into a simple json structure.
The log file is consistent and has 3 main parts (example below):
the timestamp [23 digits]
the code [4 digits]
the payload [variable digits]
Example log
2018-07-25T08:47:16,094,164f,test1
2018-07-25T08:47:18,163,1678,test2
2018-07-25T08:47:19,501,1662,test3
2018-07-25T08:47:21,278,1634,test4
2018-07-25T08:47:23,347,1632,test5
2018-07-25T08:47:24,686,1665,test6
2018-07-25T08:47:26,463,1678,test7
2018-07-25T08:47:28,533,1678,test8
2018-07-25T08:47:29,877,1632,test9
2018-07-25T08:47:31,687,1632,test10
From this I wanted to create a JSON file that would incorporate well the information inside. This is what I came up with (using org.json.JSONObject library).
BufferedReader reader = new BufferedReader(new FileReader ("file.log"));
String line = null;
String timestamp = null;
String eventCode = null;
String payload = null;
JSONObject codePayload = new JSONObject();
JSONObject finalString = new JSONObject();
for (int i = 0; i < 10; i++) {
line = reader.readLine();
timestamp = line.substring(0, 23);
eventCode = line.substring(24, 28);
payload = line.substring(29, line.length());
codePayload.put("ID", eventCode);
codePayload.put("PL", payload);
finalString.put(timestamp, codePayload);
codePayload = new JSONObject();
}
System.out.println(finalString.toString());
This little snippet should work quite well (don't mind the for) and it kinda does. It creates the JSON file according to the string I give it but it puts then in a strange order, see below.
{
"2018-07-25T08:47:24,686": {
"ID": "1665",
"PL": "test6"
},
"2018-07-25T08:47:29,877": {
"ID": "1632",
"PL": "test9"
},
"2018-07-25T08:47:31,687": {
"ID": "1632",
"PL": "test10"
},
"2018-07-25T08:47:16,094": {
"ID": "164f",
"PL": "test1"
},
"2018-07-25T08:47:21,278": {
"ID": "1634",
"PL": "test4"
},
"2018-07-25T08:47:18,163": {
"ID": "1678",
"PL": "test2"
},
"2018-07-25T08:47:23,347": {
"ID": "1632",
"PL": "test5"
},
"2018-07-25T08:47:28,533": {
"ID": "1678",
"PL": "test8"
},
"2018-07-25T08:47:19,501": {
"ID": "1662",
"PL": "test3"
},
"2018-07-25T08:47:26,463": {
"ID": "1678",
"PL": "test7"
}
}
As you can clearly see it places the objects in the wrong order and I really don't know why. If someone has the slightest idea on how this problem could occur please comment below. Thanks a lot!

The org.json.JSONObject is un-ordered, so better to use javax.json.JSONObject OR if you are using org.json library, use the org.json.JSONArray to store the timestamps in order.

Related

Issue in parsing a BufferedReader object

I need to read the output of a BufferedReader object which is in json format, parse the json and extract some values. My code looks as below:
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc1.getInputStream()));
Stream<String> s = reader.lines();
Object[] t = s.toArray();
String result = Arrays.toString(t);
JSONParser jp = new JSONParser();
JSONArray jArr = (JSONArray) jp.parse(result);
System.out.println(jArr);
The JSONArray jArr looks as below:
[
{
"result": {
"totalSize": 1,
"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
],
"done": true
},
"status": 0
}
]
I need to get the properties of "records". I have the subsequent code working, just need to create a json object with the values inside "records". Output json object required is:
{"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
I am facing json array and json object incompatibility issues while trying to case jArr as json object. Can someone suggest a way to do this
Join the stream as a single String. Use try-with-resources so the BufferedReader gets closed.
String result;
try (Stream<String> stream = reader.lines()) {
result = stream.collect(Collectors.joining());
}

How to convert all json file. Program read path of JSON file

I try convert json file to object, it run when i use one trans-unit but appears problem when i try read two trans unit. Program read only path of json. I use JSONParser and JSONObject
JSONParser jsonParser = new JSONParser();
JSONObject obj = (JSONObject) jsonParser.parse(new FileReader(args[1]));
JSONObject transUnit = (JSONObject) obj.get("trans-unit");
id = (String) transUnit.get("id");
if (id == null) {
System.out.println("Id is required parameter!");
return;
}
source = (String) transUnit.get("source");
JSONObject targetList = (JSONObject) transUnit.get("target");
if (targetList != null) {
qualifier = (String) targetList.get("state-qualifier");
targetText = (String) targetList.get("target-text");
}
JSONObject altTransList = (JSONObject) transUnit.get("alt-trans");
if (altTransList != null) {
extype = (String) altTransList.get("extype");
match = (String) altTransList.get("match-quality");
origin = (String) altTransList.get("origin");
sourceAlt = (String) altTransList.get("source");
targetAlt = (String) altTransList.get("target");
}
It run, when I read json file below
"trans-unit": {
"id": "t1",
"source": "Text text text text",
"target": {
"state-qualifier": "exact-match",
"target-text": "Tekst tekst tekst tekst",
},
"alt-trans": {
"extype": "exact-match",
"match-quality": "100%",
"source": "Text text text text",
"target": "Tekst tekst tekst tekst"
}
}
}
But when a read this json:
{
"trans-unit": {
"id": "t1",
"source": "Text text",
"target": {
"state-qualifier": "match",
"target-text": "Tekst tekst"
},
"alt-trans": {
"extype": "match",
"match-quality": "100%",
"source": "Text text",
"target": "Tekst tekst"
}
},
"trans-unit": {
"id": "t2",
"source": "Hello there.",
"target": {
"state-qualifier": "mt",
"target-text": "Cześć"
},
"alt-trans": {
"extype": "TRANSLATION",
"match-quality": "nmt",
"source": "Hello there.",
"target": "Cześć"
}
}
}
JSON dont't read trans unit with id t1 but read only tran-unit t2.
I don't know where the problem lies. Can anyone help?
What do you really want to achieve?
I think the problem is, that the second json data is kind of List or Array.
So you only will get the last "object".
Are you allowed to use any library like gson ? This will make it a lot easier.

JSON Unterminated object at character android

I have a .json file that contains JSON data. I created this file by simply Ctrl + C and Ctrl + V (from server output) Here's part of my file
[{
"ID": "109",
"objectTypeID": "1",
"names": [{
"ID": 1,
"code": "lt",
"value": "Trak\u0173 salos pilis "
}, {
"ID": 2,
"code": "en",
"value": "Trakai Island Castle"
}, {
"ID": 3,
"code": "ru",
"value": "\u0422\u0440\u0430\u043a\u0430\u0439\u0441\u043a\u0438\u0439 \u0437\u0430\u043c\u043e\u043a"
}, {
"ID": 4,
"code": "de",
"value": "Kasteel van Trakai"
}],
"descriptions": [{
"ID": 1,
"code": "lt",
"value": "<div><strong>Paslap\u010di\u0173 m\u0117g\u0117jams ir ieškotojams<\/strong><\/div>\r\n\r\n<div>Tiems, kurie domisi istorija, kurie m\u0117gsta paslaptingas vietoves, \u012f Trakus atkeliauti b\u016btina. Trak\u0173 pilis yra vienas labiausiai turist\u0173 lankom\u0173 objekt\u0173 Lietuvoje......"
}]
}]
I have saved this file with utf-8 encoding
As you can see there are lot of Unicode Characters and html elements like <div>, <strong> and so on....
Now I want to parse this file. Here's my java/android code
private String getJSONString(File file){
try {
FileInputStream is = new FileInputStream(file.getAbsolutePath());
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void object_parser(File file){
String jsonString = getJSONString(file);
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonString);
Log.d("OBJECTS_LIST_AAA", jsonArray.toString());
} catch (JSONException e) {
Log.d("OBJECTS_LIST_ERROR", e.getMessage()); // print error
e.printStackTrace();
}
}
}
and I get this error Unterminated object at character 5641 of [{"ID":"109","objectTypeID":"1","names":[{"ID":1,"code":"lt","value":"Trak\u0173 salos pilis "},......
I think that formating is missing in this file.
Your Every "Restaurant "Avilys"" like data are invalid, You have to replace all of them with "Restaurant Avilys" as a single String value quoted with only two quotation marks. There are many similar cases like these as well. And note that the part you posted is clearly valid and can be parsed easily, Here is no such errors.

How to decode JSONObject

This question is related with my previous question
I can successfully get the String in json format from the URL to my spring controller
Now I have to decode it
so I did like the following
#RequestMapping("/saveName")
#ResponseBody
public String saveName(String acc)
{jsonObject = new JSONObject();
try
{
System.out.println(acc);
org.json.JSONObject convertJSON=new org.json.JSONObject(acc);
org.json.JSONObject newJSON = convertJSON.getJSONObject("nameservice");
System.out.println(newJSON.toString());
convertJSON = new org.json.JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("id"));
}
catch(Exception e)
{
e.printStackTrace();jsonObject.accumulate("result", "Error Occured ");
}
return jsonObject.toString();
}
This is the JSON String { "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
When I run the code then I get the error
org.json.JSONException: JSONObject["nameservice"] is not a JSONObject.
What wrong I am doing?
It's not a JSONObject, it's a JSONArray
From your question:
{ "nameservice": [ { "id": 7413, "name": "ask" }, { "id": 7414, "name": "josn" }, { "id": 7415, "name": "john" }, { "id": 7418, "name": "RjhjhjR" } ] }
The [ after the nameservice key tells you it's an array. It'd need to be a { to indicate an object, but it isn't
So, change your code to use it as a JSONArray, then iterate over the contents of that to get the JSONObjects inside it, eg
JSONArray nameservice = convertJSON.getJSONArray("nameservice");
for (int i=0; i<nameservice.length(); i++) {
JSONObject details = nameservice.getJSONObject(i);
// process the object here, eg
System.out.println("ID is " + details.get("id"));
System.out.println("Name is " + details.get("name"));
}
See the JSONArray javadocs for more details
It seems you're trying to get a JSONObject when "nameservice" is an array of JSONObjects and not an object itself. You should try this:
JSONObject json = new JSONObject(acc);
JSONArray jsonarr = json.getJSONArray("nameservice");
for (int i = 0; i < jsonarr.length(); i++) {
JSONObject nameservice = jsonarr.getJSONObject(i);
String id = nameservice.getString("id");
String name = nameservice.getString("name");
}
I don't understand why you do it manualy if you already have Spring Framework.
Take a look at MappingJackson2HttpMessageConverter and configure your ServletDispatcher accordingly. Spring will automatically convert your objects to JSON string and vice versa.
After that your controller method will be looked like:
#RequestMapping("/saveName")
#ResponseBody
public Object saveName(#RequestBody SomeObject obj) {
SomeObject newObj = doSomething(obj);
return newObj;
}

how to retrieve JSON object from the JSON array

I am having the below JSON. Inside this JSON I am having "ticketDetails" as JSON array. From this array I want to retrieve the value of ticketPrice inside the json object "amount". How can I do that?
{
"ticketDetails": [{
"seq": 1,
"qty": 2,
"amount": {
"ticketPrice": 120,
"bookingFee": 50
},
"session": {
"id": 1001,
"date": "2013, 9, 15",
"time": "1300"
},
"venue": {
"id": "MTRG",
"name": "Adlabs Manipur",
"companyCode": "ADLB"
},
"event": {
"id": "ET00000001123",
"name": "Chennai Express",
"producerCode": "YRF"
},
"category": {
"ttypeCode": "00012",
"areaCatCode": "2414",
"type": "Gold",
"price": 270
}
}]
}
Any suggestion will helpful...
Below is the sample code for retrieving the ticketPrice from the given JSONObject:
JSONObject objData = (JSONObject)JSONSerializer.toJSON(data);
JSONArray objTicketDetailsJsonArr = objData.getJSONArray("ticketDetails");
for(int nSize=0; nSize < objTicketDetailsJsonArr.size(); nSize++){
String ticketPrice = "";
ticketPrice = objTicketDetailsJsonArr.getString("ticketPrice");
}
Below are the imports for the above code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
source of JAR: http://json-lib.sourceforge.net/
you store your data within a variable
data = {...}
then you access it this way:
data.ticketDetails[0].amount.ticketPrice
if the ticketDetails have more than one element
you can loop over the ticketDetails array and store all the ticketPrice values within an other array, ticketPriceArray
the following would work fine in JavaScript:
var ticketPriceArray = data.ticketDetails.map(function(k){
return k.amount.ticketPrice;
});
if you are using another programming language a general loop would work fine also
for ( i; i< ticketDetails.length ; i++){
ticketPriceArray[i] = data.ticketDetails.amount.ticketPrice[i];
}
For Java check this tutorial:
http://answers.oreilly.com/topic/257-how-to-parse-json-in-java/
you can try this code:
JsonObject transactiondata = (JsonObject)Offer.get("transData");
JsonObject ticketdata = (JsonObject)transactiondata.get("tickets");
JsonObject offerData = (JsonObject)Offer.get("offerData");
JsonObject offerData1 = (JsonObject)offerData.get("offerconfig");
JsonArray jsonarr= (JsonArray)ticketdata.get("ticketDetails");
double ticketPrice = Double.parseDouble(jsonarr.get(0).getAsJsonObject().get("amount").getAsJsonObject().get("ticketPrice").getAsString());
System.out.println("ticketPrice:"+ticketPrice);

Categories