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

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.

Related

Java : JSONObject.put looped gives wrong order?

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.

Json data parsing and display in List using Codename one

Here I have to parse JSON data getting from Facebook and display in list using Codename one so how can I cast ArrayList with Map.
Here is my Json data
{
"posts": {
"data": [
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-14T19:08:34+0000",
"id": "1323317604429735_1307213186040177"
},
{
"story": "Gaurav Takte shared a link.",
"created_time": "2017-02-02T14:22:50+0000",
"id": "1323317604429735_1295671703860992"
},
{
"message": "Hurray....... INDIA WON KABBADI WORLD CUP 2016",
"created_time": "2016-10-22T15:55:04+0000",
"id": "1323317604429735_1182204335207730"
},
{
"story": "Gaurav Takte updated his profile picture.",
"created_time": "2016-10-21T05:35:21+0000",
"id": "1323317604429735_1180682575359906"
},
{
"message": "Friends like all of you … I would love to keep forever.
#oldmemories with # besties
#happydays",
"story": "Gaurav Takte with Avi Bhalerao and 5 others.",
"created_time": "2016-10-21T05:33:55+0000",
"id": "1323317604429735_1180682248693272"
},
{
"message": "\"सर्वांना गणेशचतुर्थीच्या हार्दीक शुभेच्छा.
तुमच्या मनातील सर्व मनोकामना पूर्ण होवोत , सर्वांना
सुख, समृध्दी, ऎश्वर्य,शांती,आरोग्य लाभो हीच
बाप्पाच्या चरणी प्रार्थना. \"
गणपती बाप्पा मोरया , मंगलमुर्ती मोरया !!!",
"story": "Gaurav Takte with Avi Bhalerao and 18 others.",
"created_time": "2016-09-05T05:06:58+0000",
"id": "1323317604429735_1133207030107461"
}
]
}
}
So how can I parse it and also display in list manner in Codename one.
Check out the JSONParser class in Codename One which the developer guide covers.
The sample from the guide is pasted below but I suggest reading it there as it is properly annotated there:
Form hi = new Form("JSON Parsing", new BoxLayout(BoxLayout.Y_AXIS));
JSONParser json = new JSONParser();
try(Reader r = new InputStreamReader(Display.getInstance().getResourceAsStream(getClass(), "/anapioficeandfire.json"), "UTF-8")) {
Map<String, Object> data = json.parseJSON(r);
java.util.List<Map<String, Object>> content = (java.util.List<Map<String, Object>>)data.get("root");
for(Map<String, Object> obj : content) {
String url = (String)obj.get("url");
String name = (String)obj.get("name");
java.util.List<String> titles = (java.util.List<String>)obj.get("titles");
if(name == null || name.length() == 0) {
java.util.List<String> aliases = (java.util.List<String>)obj.get("aliases");
if(aliases != null && aliases.size() > 0) {
name = aliases.get(0);
}
}
MultiButton mb = new MultiButton(name);
if(titles != null && titles.size() > 0) {
mb.setTextLine2(titles.get(0));
}
mb.addActionListener((e) -> Display.getInstance().execute(url));
hi.add(mb);
}
} catch(IOException err) {
Log.e(err);
}
hi.show();
Try this,
JSONObject obj=new JSONObject(response);
JSONObject posts_obj=obj.getJSONObject("posts");
JSONArray data_arr=posts_obj.getJSONArray("data");
for(int i=0;i<data_arr.length();i++) {
JSONObject data_obj=data_arr.getJSONObject(i);
String story = data_obj.getString("story");
String created_time = data_obj.getString("created_time");
String id = data_obj.getString("id");
if(data_obj.has("message")) {
String message = data_obj.getString("message");
}
}

How to fetch all the nodes and child nodes of JSON object in java?

I want to fetch all the nodes of the below JSON object. For example
result, identification, payment etc.
{
"result": {
"identification": {
"transactionid": "Merchant Assigned ID",
"uniqueid": "d91ac8ff6e9945b8a125d6e725155fb6",
"shortid": "0000.0005.6238",
"customerid": "customerid 12345"
},
"payment": {
"amount": "2400",
"currency": "EUR",
"descriptor": "order number"
},
"level": 0,
"code": 0,
"method": "creditcard",
"type": "preauthorization",
"message": "approved",
"merchant": {
"key1": "Value1",
"key0": "Value0"
}
},
"id": 1,
"jsonrpc": "2.0"
}
I have used the following code:
JSONObject partsData = new JSONObject(returnString);
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String result=iterator.next();
System.out.println(result);
}
But the result I am getting is:
id
result
jsonrpc
How do I get all the node names?
Move your iterator logic (to iterate over json) in a method
e.g.,
public Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
Iterator<String> keys = json.keys();
while(keys.hasNext()){
String key = keys.next();
String val = null;
if ( json.getJSONObject(key) instanceof JSONObject ) {
JSONObject value = json.getJSONObject(key);
parse(value,out);
}
else {
val = json.getString(key);
}
if(val != null){
out.put(key,val);
}
}
return out;
}
This way you can check for each sub node in the json object.
You have to parse through all the objects.
JSONObject partsData = new JSONObject("result");
JsonObject identification = partsData.getJsonObject("identification");
JsonObject payment = partsData.getJsonobject("payment");

Parsing a JSON object within a JSON object

I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));

Nested JSONObject

I am having several problems with JSONObjects and JSONArray.
I would like to parse this json file:
[{
"SourceFile": "AndresIniesta.flv",
"ExifTool": {
"ExifToolVersion": 8.22
},
"System": {
"FileName": "AndresIniesta.flv",
(...)
},
"File": {
"FileType": "FLV",
"MIMEType": "video/x-flv"
},
"Flash": {
"Duration": "04:09",
"Starttime": 0,
"Totalduration": 249.36,
"ImageWidth": 320,
(...)
},
"Composite": {
"ImageSize": "320x240"
}
}]
But not all of them, just the field Flash.
The whole file is an JSONArray, but with just 1 element. I got the Flash filled with this piece of code:
JsonMappingException, IOException {
String a = new String();
InputStream is =
this.getClass().getClassLoader().getResourceAsStream(
"a.json");
String jsonTxt = IOUtils.toString(is);
JSONArray json = (JSONArray) JSONSerializer.toJSON(jsonTxt);
JSONObject flash = json.getJSONObject(0);
System.out.print("flash -> " + flash.getString("Flash"));
But I don't know hoy to access to each one of Flash fild, lis Duration, Starttime... etc.
When I try it like this:
String canseekontime =
flash.getString("Canseekontime");
int starttime =
flash.getInt("Starttime");
Double duration = flash.getDouble("Duration");
I get this error:
net.sf.json.JSONException: JSONObject["Duration"] not found.
Any help??
Thanks in advance
You mean
JSONObject flash = json.getJSONObject(0);
JSONObject Flash = flash.getJSONObject("Flash");
int starttime = Flash.getInt("Starttime");

Categories