Can't access variable in JSON - java

I'm having trouble with my JSONObject
this is my code :
importPackage(Packages.org.apache.commons.io);
importPackage(Packages.java.io);
fisTargetFile = new FileInputStream(new File("C:/moe.json"));
input = IOUtils.toString(fisTargetFile, "UTF-8");
jsonData = input;
myJSONObject = eval('(' + jsonData + ' )');
len = myJSONObject.cells.length;
count = 0;
if (count < len) {
var name = myJSONObject.cells[count].attrs.text;
var type = myJSONObject.cells[count].type;
var photo = myJSONObject.cells[count].attrs.image.xlink:href;
row["name"] = name;
row["type"] = type;
// row["photo"] = photo;
count++;
return true;
}
return false;
My problem is in this line var photo = myJSONObject.cells[count].attrs.image.xlink:href;
i can't access my Image data because this is not a correct syntax ":" how can i overcome it ? is there a way to escape the ":" ?
Edit :
this is my JSON object :
{
"cells": [
{
"type": "basic.Platform",
"size": {
"width": 60,
"height": 60
},
"custom": {
"identifier": [
{
"name": "Name1",
"URI": "Value1"
}
],
"classifier": [
{
"name": "Name2",
"URI": "Value2"
}
],
"output": [
{
"name": "Name3",
"URI": "Value3"
}
],
"imported": false,
"event": [
]
},
"ref": [
],
"uuid": [
"dc537ba7-b9dc-476e-9f09-8c1f5211f9bb"
],
"position": {
"x": 390,
"y": 230
},
"angle": 0,
"id": "dc537ba7-b9dc-476e-9f09-8c1f5211f9bb",
"embeds": "",
"z": 1,
"description": "",
"attrs": {
"text": {
"font-size": "9",
"text": "rere",
"ref-x": "0.5",
"ref-dy": "20",
"fill": "#000000",
"font-family": "Arial",
"display": "",
"stroke": "#000000",
"stroke-width": "0",
"font-weight": "400"
},
"image": {
"width": 50,
"height": 50,
"xlink:href": "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG4AAACWCAYAAAA\/mr2PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS5EOsBjwfqm3fvx0eIfsT89"
}
}
}
]
}
I have trimmed the xlink:href data because it's too long.

Yes there is
myJSONObject.cells[count].attrs.image["xlink:href"]
Reasoning: Any where you use the dot notation to separate object references you can also use the square bracket notation and pass in a string. This is the standard way to reference something that is not a "valid" identifier such as a colon in the middle of a name.

In JavaScript, objects are also associative arrays (or hashes).
That is, the property foo.bar can also be read or written by calling foo["bar"]
var photo = myJSONObject.cells[count].attrs.image["xlink:href"];

You may try to access it like a property of image["xlink:href"].
Or please specify what that column stands for.

Related

Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1

I have a json file which I got from my backend.
The json file is as follows.
{
"documentTemplate": {
"pageFormat": {
"pageWidth": "50",
"pageLength": "13",
"usePageLengthFromPrinter": false
},
"template": {
"header": [
" Delivery Order ",
"Date : ${date} NO. : ${no_surat} ",
"Customer: ${customer} Delivery Date: ${delivery_date}"
],
"detail": [
{
"table": "table_details",
"border": "true",
"columns": [
{
"source": "description",
"width": 9,
"caption": "DESCRIPTION"
},
{
"source": "do_hanwa_and_date",
"width": 9,
"caption": "DO HW / DATE HW"
},
{
"source": "qty",
"width": 9,
"caption": "QTY"
},
{
"source": "nett",
"width": 9,
"caption": "NETT"
},
{
"source": "gross",
"width": 9,
"caption": "GROSS"
},
{
"source": "size",
"width": 9,
"caption": "SIZE"
},
{
"source": "location",
"width": 9,
"caption": "LOCATION"
},
{
"source": "urut",
"width": 9,
"caption": "URUT"
}
]
},
" ",
" ",
" ___________ ___________ ",
" (Signature) (Signature) "
]
}
},
"documentValue": {
"date": "13-05-2019",
"no_surat": "01024/05/DO-MARU/19JKT",
"customer": "PT. WIJAYA STEELINDO",
"delivery_date": "13-05-2019",
"table_details": [
{
"description": "03NKBTL190205005/12",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,568",
"gross": "4,616",
"size": "0.70MM X 151.8MM",
"location": "PT2212",
"urut": 64592
},
{
"description": "03NKBTL190204997/04",
"do_hanwa_and_date": "46916 / 29-03-2019",
"qty": "1",
"nett": "4,504",
"gross": "4,552",
"size": "0.70MM X 151.8MM",
"location": "PU5111",
"urut": 64591
}
]
}
}
To process the data: I use Gson.
public class Report {
String filePathString;
public HashMap<String, String> convertJsonToObject() {
Gson gson = new Gson();
try (JsonReader reader = new JsonReader(new FileReader(this.filePathString) )) {
// Converting JSON File to Java Object
HashMap<String, String> hashMapResult = gson.fromJson(reader, HashMap.class);
return hashMapResult;
} catch (IOException e) {
}
return null;
}
It's time to use the data from the GSON converter.
I use JSwing.
private void jButtonCompileGsonActionPerformed(java.awt.event.ActionEvent evt) {
// Create a report, param => file`s path
Report report = new Report(jTextFieldPathFile.getText());
// Read the file, as the return is a hashMap
HashMap<String, String> result = report.convertJsonToObject();
// Get based key
String documentTemplate = String.valueOf(result.get("documentTemplate")).replaceAll("\r?\n", "");
String documentValue = String.valueOf(result.get("documentValue")).replaceAll("\r?\n", "");
// Just to clarify
System.out.println(documentTemplate);
System.out.println(documentValue);
}
The result is:
documentTemplate => {pageFormat={pageWidth=50, pageLength=13, usePageLengthFromPrinter=false}, template={header=[ Delivery Order , Date : ${date} NO. : ${no_surat} , Customer: ${customer} Delivery Date: ${delivery_date}], detail=[{table=table_details, border=true, columns=[{source=description, width=9.0, caption=DESCRIPTION}, {source=do_hanwa_and_date, width=9.0, caption=DO HW / DATE HW}, {source=qty, width=9.0, caption=QTY}, {source=nett, width=9.0, caption=NETT}, {source=gross, width=9.0, caption=GROSS}, {source=size, width=9.0, caption=SIZE}, {source=location, width=9.0, caption=LOCATION}, {source=urut, width=9.0, caption=URUT}]}, , , ___________ ___________ , (Signature) (Signature) ]}}
documentValue => {date=13-05-2019, no_surat=01024/05/DO-MARU/19JKT, customer=PT. WIJAYA STEELINDO, delivery_date=13-05-2019, table_details=[{description=03NKBTL190205005/12, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,568, gross=4,616, size=0.70MM X 151.8MM, location=PT2212, urut=64592.0}, {description=03NKBTL190204997/04, do_hanwa_and_date=46916 / 29-03-2019, qty=1, nett=4,504, gross=4,552, size=0.70MM X 151.8MM, location=PU5111, urut=64591.0}]}
I use this library: SimpleESCP
From these libraries, the interpretation is as follows.
import javax.json.JsonObject;
public class JsonDataSource implements DataSource {
private static final Logger LOG;
private JsonObject source;
public JsonDataSource(String jsonString){
}
}
I use it like this and get the following error message:
JsonDataSource jsonDataSource = new JsonDataSource(documentValue);
Exception in thread "AWT-EventQueue-0" javax.json.stream.JsonParsingException: Unexpected char 100 at (line no=1, column no=2, offset=1)
Please help and advice.
Thank you.

how to update existing JSON file in java

This is my sample Json
{
"State": {
"version": "1",
"SName": "Test",
"shippingDetails": {
"Address1": "AP",
"ZipCode": "1236"
},
"Directions": {
"routes": [
{
"taxAmount": "0.0",
"Quantity": "5",
"bounds": {
"SerialVersion": [
{
"text": "1.7 km",
"value": "1729",
"time": "02633"
},
{
"text": "1.9 km",
"value": "1829",
"time": "02353"
},
{
"text": "17 km",
"value": "1059",
"time": "02133"
}
]
}
}
]
}
}
}
I want to update SName, ZipCode,taxAmount,Quantity, and text[1] values
are there any way to do this. I am taking JSON in a file and update tags are taking into HashMap
JSONObject jsonObject = new JSONObject("Your_JSON_String");
JSONObject jsonObjectForState = jsonObject.getJSONObject(“State”);
jsonObjectForState.put("Sname", "New_Value_Here");
put(...) will replace the current value with new value. Similarly, you can update the other values. Once you are done, you can convert it back using:
jsonObject.toString();
And write it back to the file.

Dynamic JSON Model

Here, I'm trying to parse this JSON Object into model. But I'm stuck here with the dynamic field names. Here is the example of the JSON Object
{
"1": {
"state": {
"on": false,
"bri": 0,
"hue": 0,
"sat": 0,
"effect": "none",
"xy": [
0,
0
],
"ct": 0,
"alert": "none",
"colormode": "hs",
"reachable": false
},
"type": "Extended color light",
"name": "Hue Lamp 1",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5a:aa-0b",
"swversion": "5.23.1.13452"
},
"2": {
"state": {
"on": false,
"bri": 254,
"hue": 8000,
"sat": 200,
"effect": "none",
"xy": [
0.5469,
0.3819
],
"ct": 500,
"alert": "none",
"colormode": "hs",
"reachable": true
},
"type": "Extended color light",
"name": "Hue Lamp 2",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5c:55-0b",
"swversion": "5.23.1.13452"
}
}
There are these field "1","2" and so on. How to parse this into model ? Can anybody help ?
Updated :
All i want to achieve is getting this "1", "2" key value and the "name" field value in it. Thanks before !
You need to wrap json in one root element then use model like this
public class RootElement{
private Map<String, DataInfo> rootElement;
}
public class DataInfo {
private State state= null;
private String type= null;
// all your field under 1, 2
}
And your json should look like this
"rootElement": {
"1": {
"state": {
"on": false,
"bri": 0,
"hue": 0,
"sat": 0,
"effect": "none",
"xy": [
0,
0
],
"ct": 0,
"alert": "none",
"colormode": "hs",
"reachable": false
},
"type": "Extended color light",
"name": "Hue Lamp 1",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5a:aa-0b",
"swversion": "5.23.1.13452"
},
// other object
}
#tommy wu , try this
JSONObject questionMark = new JSONObject("your string containing whole json object");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}

I want to convert xml string data inside json object to json in java

Below is my json string and i want to convert data of additionalDetails into json string, but i am not able to success.
{
"docs": 70,
"size": 250,
"currentPageNo": 0,
"recordStartFrom": 0,
"columnHeader": [
{
"id": "0",
"fieldName": "id",
"imgName": "",
"tooltipSrc": "",
}
],
"data": [
{
"Number": "10000",
"price": "4.75",
"manfName": "",
"minOrderQty": "0.00",
"maxOrderQty": "0",
"additionalDetails": "<item>CUR:Rupees</item><item>code:one</item>",
},
{
"Number": "10001",
"price": "1.75",
"manfName": "",
"minOrderQty": "0.00",
"maxOrderQty": "0",
"additionalDetails": "",
}
]
}
I am trying to convert additionalDetails data into json string. I try to convert json string to XML content and XML to json string but data of additionalDetails is not converted into json string.
I've prepared some FIDDLE for You using X2JS library: http://code.google.com/p/x2js/
INDEX.HTML:
<body>
<pre id="pre_id">TEST</pre>
<button id="go_button">GO</button>
</body>
SCRIPT:
var x2js = new X2JS();
$("#go_button").click(function() {
var form_data = {
"docs": 70,
"size": 250,
"currentPageNo": 0,
"recordStartFrom": 0,
"columnHeader": [
{
"id": "0",
"fieldName": "id",
"imgName": "",
"tooltipSrc": "",
}
],
"data": [
{
"Number": "10000",
"price": "4.75",
"manfName": "",
"minOrderQty": "0.00",
"maxOrderQty": "0",
"additionalDetails": "<item>CUR:Rupees</item><item>code:one</item>",
},
{
"Number": "10001",
"price": "1.75",
"manfName": "",
"minOrderQty": "0.00",
"maxOrderQty": "0",
"additionalDetails": "",
}
]
};
for (var i=0; i<form_data.data.length; i++) {
console.log(x2js.xml_str2json(
'<additionalDetails>'+
form_data.data[i].additionalDetails+
'</additionalDetails>'));
form_data.data[i].additionalDetails = x2js.xml_str2json(
'<additionalDetails>'+
form_data.data[i].additionalDetails+
'</additionalDetails>').additionalDetails;
}
$('#pre_id').html(JSON.stringify(form_data));
});
This is not a general solution to the stated problem, but a solution to your problem.
I would use regular expressions along the lines of:
<item>([0-9a-zA-Z]*):([0-9a-zA-Z]*)</item>
If you use this expression in global mode you will match each input. You can parse the string using java.util.regex.Pattern. (See the section on "Groups and capturing" to get the values within.)
You can then build up a com.google.gson.JsonArray and populate the values from the Matcher. This array can then be replaced with the additionalDetails field.
Finally you just write out the result or do whatever you wanted to do with it.

Json : Content Parsing error

I have json file like this
[
{
"topic": "Example1",
"ref": {
"1": "Example Topic",
"2": "Topic"
},
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
}
]
I want to parse the ref array. I tried this. But showing error.
jsonArray.getJSONObject(index).getJSONArray("ref").getJSONObject(index).toString()
Now my question is
1) What is the correct way to parse that array's content.
The whole JSON is an array (starts with [). Its first element is an object (starts with {). This object has an attribute "ref". Its value is an object (starts with {).
So, to get this object, you need
jsonArray.getJSONObject(index).getJSONObject("ref")
I solved it By
JSONObject arJS = jsonArray.getJSONObject(index).getJSONObject("ref");
for(int counter = 1 ; jo<=jsonArray.getJSONObject(index).getJSONObject("ref").length();counter++){
String value = arJS.getString(String.valueOf(counter));
}

Categories

Resources