JSON object not found in JSON array - java

I am aware there are duplicate questions. I am not able to figure this out despite that.
Below is a JSON file which I receive from an API. I need to get the "year" value.
The error I am getting is:
message org.glassfish.jersey.server.ContainerException: org.json.JSONException: JSONArray[1] not found.
Which relates to the line on Java:
JSONObject year = years.getJSONObject(1).getJSONObject("years");
I also tried:
JSONObject year = years.getJSONObject(1);
Why is this code not working? Isn't index 1 clearly year in the years array?
JSON
{
"make": {
"id": 200000404,
"name": "Chevrolet",
"niceName": "chevrolet"
},
"model": {
"id": "Chevrolet_Camaro",
"name": "Camaro",
"niceName": "camaro"
},
"drivenWheels": "rear wheel drive",
"numOfDoors": "2",
"options": [],
"colors": [],
"manufacturerCode": "1EH67",
"price": {
"baseMSRP": 34180.0,
"baseInvoice": 32813.0,
"deliveryCharges": 900.0,
"usedTmvRetail": 17766.0,
"usedPrivateParty": 16321.0,
"usedTradeIn": 14755.0,
"estimateTmv": false,
"tmvRecommendedRating": 0
},
"categories": {
"market": "Performance",
"EPAClass": "Compact Cars",
"vehicleSize": "Midsize",
"primaryBodyType": "Car",
"vehicleStyle": "Convertible",
"vehicleType": "Car"
},
"vin": "2G1FC3D33C9165616",
"squishVin": "2G1FC3D3C9",
"years": [{
"id": 100531911,
"year": 2012,
"styles": [{
"id": 101395591,
"name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)",
"submodel": {
"body": "Convertible",
"modelName": "Camaro Convertible",
"niceName": "convertible"
},
"trim": "LT"
}]
}],
"matchingType": "SQUISHVIN",
"MPG": {
"highway": "28",
"city": "17"
}
}
JAVA
public String vehicleData(#PathParam("vin") String vin,
#PathParam("key") String key) throws Exception {
GetVehicleJSON jsonData = new GetVehicleJSON(vin, key);
JSONObject data = jsonData.getVehicleData();
String name = data.getJSONObject("make").getString("name");
String highway = data.getJSONObject("MPG").getString("highway");
String city = data.getJSONObject("MPG").getString("city");
JSONArray years = data.getJSONArray("years");
JSONObject year = years.getJSONObject(1).getJSONObject("years");
String s = year.getString("year");
return name + " " + s + " " + highway + " " + city;
}

You're working with JSON array whose indexing is zero-based. Do it as:
JSONArray years = data.getJSONArray("years");
String year = years.getJSONObject(0).getString("year");

Your json shows that the years value is an array with 1 element and inside that element is an object:
"years": [{ "id": 100531911, "year": 2012, "styles": [{ "id": 101395591, "name": "LT 2dr Convertible w/2LT (3.6L 6cyl 6M)", "submodel": { "body": "Convertible", "modelName": "Camaro Convertible", "niceName": "convertible" }, "trim": "LT" }] }],
Because array element numbering begins at 0, that means if you select element 1 you will get this error:
message org.glassfish.jersey.server.ContainerException: org.json.JSONException: JSONArray[1] not found.
To fix it you need to select element 0 instead of 1:
years.getJSONObject(0);

Related

How to access an int inside of a array in a JSON file

I have a JSON file holding students name, id, and grades. I managed to print the name and id, but cannot figure out how to access the grades ("score").
Part of my JSON file (3 other students) :
"Name": "Abstract Data Types",
"CRN": "14607",
"Capacity": 24,
"Code": "cs241",
"Time": "13:50",
"Number of Sections": 1,
"Students": [
{
"name": "David",
"id": "987654321",
"course works":[
{
"name": "q1",
"score": 2
},{
"name": "q2",
"score": 10
},{
"name": "q3",
"score": 10
},{
"name": "midterm",
"score": 89
},{
"name": "final",
"score": 95
}
]
}
So, I managed to print "name" and "id" with :
for (JsonValue value : studentsArray) {
String name = value.asJsonObject().getString("name");
String id = value.asJsonObject().getString("id");
if (value.asJsonObject().getString("name").equalsIgnoreCase(commandInput)) {
System.out.println("Name: " + name + " | " + "ID: " + id + " | ");
}
}
I cannot figure out how to now print q1-final grades. I keep receiving errors saying the value is null.
I have tried just doing something like:
int q1 = value.asJsonObject().getInt("score");
hoping it would at at least print all of the grades (and not just quiz 1, like I need), but instead gave the error:
Cannot invoke "javax.json.JsonNumber.intValue()" because the return value of "org.glassfish.json.JsonObjectBuilderImpl$JsonObjectImpl.getJsonNumber(String)" is null

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.

Rest-assured. get value from another value

I have a json response something like this:
"results": [
{
"id": "1",
"name": "YYY",
"shortName": "Y"
},
{
"id": "2",
"name": "XXX",
"shortName": "X"
},
{
"id": "3",
"name": "ZZZ",
"shortName": "Z"
}
]
I want to get id value when I send name value. For example if name = ZZZ return me id value in this case 3 using rest assured
Json path json-path-2.9.0 with rest-assured
import static com.jayway.restassured.path.json.JsonPath.from;
below JsonPath query
from(response).getList("results.findAll { it.name=='ZZZ' }.id").toString() //returns 3
from(response).getList("results.findAll { it.name=='XXX' }.id").toString() //returns 2

how to calculate total value for the below JSON value U.O.M Wise in Java

how to calculate total value for the below JSON value U.O.M Wise in Java?
sequence can be vary. We cannot expect number of uoms and sequence of results.
i have created hashset and made unique uom.
{
value=100
uom=kg
},
{
value=200
uom=kg
},
{
value=100
uom=lt
},
{
value=100
uom=ab
},
{
value=100
uom=lt
}
Please provide some code ref
This is not valid JSON as it uses = as key\value separator (change to something like this and use tools like JSONLint to validate):
[{
"value": "100",
"uom": "kg"
}, {
"value": "200",
"uom": "kg"
}, {
"value": "100",
"uom": "lt"
}, {
"value": "100",
"uom": "ab"
}, {
"value": "100",
"uom": "lt"
}
]
Even having this structure you can parse it into a collection of touples (value, uom) and then just sum everything having same uom
For example you can use this:
javax.json.JsonArray body = Json.createReader(new StringReader(YOUR_JSON_STRING)).readArray();
and read a JSON to array of touples

Can't access variable in JSON

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.

Categories

Resources