Parse String array out of JSON Array - java

I am having this in JSONArray ary2;
JSON string is :
[
{
"item_id": "1",
"Head_item_id": "1",
"major_item_id": "1",
"Quantity": "10",
"selling_prize": "20",
"MRP": "90",
"title": "JK Lakshmi PPC Cement",
"SKU": "B2WBUICEM2"
},
{
"item_id": "2",
"Head_item_id": "1",
"major_item_id": "1",
"Quantity": "10",
"selling_prize": "30",
"MRP": "80",
"title": "JK Lakshmi PPC Cement",
"SKU": "B2WBUICEM2"
},
{
"item_id": "3",
"Head_item_id": "1",
"major_item_id": "1",
"Quantity": "10",
"selling_prize": "10",
"MRP": "70",
"title": "Shree Ultra OPC 43 Grade Cement",
"SKU": "B2WBUICEM5"
}
]
I want to get String array for each attribute , like :
String[] item_id;
String[] Head_item_id;
etc.
unable to get it. Please help.

Try This:
JSONArray arr = new JSONArray(yourJSONresponse);
String[] item_id=new String[array.length()];
String[] Head_item_id=new String[arr .length()];
for(int i = 0; i < arr.length(); i++){
item_id[i]=arr.getJSONObject(i).getString("item_id");
Head_item_id[i]=arr.getJSONObject(i).getString("Head_item_id");
}

You need to follow these steps:
-> Create POJO for your JSON data and provite getters and setters for each attribute.
-> Parse your JSON data using GSON
-> get the desired attribute(using getters) and store it in the respective string array

Related

How to do Parsing JSON string in Java with nested arrays

Starting from the similar question,
Nested JSON Array in Java
I have a somewhat odd json as a response from a REST api(POST) call. I need to find out the id and name of the sub_items array in each items array element.
I tried like given below for which I am getting error like
org.json.JSONException: JSONObject["items.sub_items"] not found.
I also tried just 'sub_items' as the parameter also, but no. I am using GSON. No choice use others.
final JSONObject jsonObj = new JSONObject(JSON_STRING);
final JSONArray subItems = jsonObj.getJSONArray("items.sub_items");
final int n = subItems.length();
for (int i = 0; i < n; ++i) {
final JSONObject subI= subItems.getJSONObject(i);
System.out.println("id="+subI.getString("id"));
System.out.println("name="+subI.getString("name"));
}
The following is my json as a response from a REST api call.
{
"menu": {
"items": [{
"id": 1,
"code": "hot1_sub1_mnu",
"name": "Mutton",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Mutton Pepper Fry",
"price": "100"
}, {
"id": "02",
"name": "Mutton Curry",
"price": "100"
}]
},
{
"id": "2",
"code": "hot1_sub2_mnu",
"name": "Sea Food",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Fish Fry",
"price": "150"
}]
},
{
"id": "3",
"code": "hot1_sub3_mnu",
"name": "Noodles",
"status": "1",
"sub_items": [{
"id": "01",
"name": "Chicken Noodles",
"price": "70"
}, {
"id": "02",
"name": "Egg Noodles",
"price": "60"
}]
}
]
}}
As I said, my JSON is a response from an REST api call, and it is 7300 lines long, like shown below with the outline, as shown in code beautifier.
object {3}
infoTransferReqResp {1}
paramExtens : null
pageGroups {1}
pageGroups [1]
0 {4}
page_group_name : LFG - LG - Insured Summary
page_group_id : 8100
**pages [3]**
repeatingBlocks {1}
I needed to extract a string value 'questionText' from inside 'Pages' array. I used jsonPath() method with navigation path as given below which solved the problem.
JsonPath jsonPathEvaluator = response.jsonPath();
List<List<List<String>>> questions = jsonPathEvaluator.getList("pageGroups.pageGroups.pages.questions.questionText");
It gave me 3 ArrayLists one embedded in another corresponding to 3 arrays of 'pages'

Get JSONArray's Key String

Im making an app thats dynamic to a json template (the app reads the template from the internet) and i need to read a JSONArray's key string.
my json:
{
"format": {
"Drive": [
"Mecanum",
"Omni",
"Regular"
],
"Drive-Configuration": [
"H",
"X"
],
"Glyph-Elevator": [
"Parallel Elevator",
"Stick Elevator",
"Strip Elevator"
],
"Glyph-Picker": [
"Strip Picker",
"Dual-Servo Picker"
],
"Relic-Elevator": [
"Horizontal Parallel"
],
"Relic-Holder": [
"Pliers",
"Dual-Servo With Rubber Pads"
],
"CypherBox-Fill": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"Autonomous": [
"Poor",
"Minimal",
"Okay",
"Good",
"Almost Perfect",
"Perfect"
]
}
}
what i want is to read the "Drive" and the "Drive-Configuration" names by code.
what i have:
JSONObject reader=new JSONObject(template);
JSONArray config=reader.getJSONArray("format");
for(int type=0;type<config.length();type++){
JSONArray con=config.getJSONArray(type);
//Here I Want To Read The Array's Name
}
Instead of JSON Parser use GSON.!
add this to your gradle
compile 'com.google.code.gson:gson:2.8.1'
Create a ClassMain.!
class MainClass{
#SerializedName("format")
Value format;
}
Class value{
#SerializedName("Drive")
ArrayList<String> drive;
#SerializedName("Drive-Configuration")
ArrayList<String> driveConfiguration;
generate getter and setter.!
}
and then Convert your JSON to GSON.!
MainClass mainClass= new Gson().fromJson(json.toString(), MainClass.class);
mainClass.getFormat().getDirve();
Used JSONObject.names();
to read the names
ArrayList<Template> tm = new ArrayList<>();
JSONObject reader = new JSONObject(format);
JSONObject config = reader.getJSONObject("format");
Iterator<String> types = config.keys();
while (types.hasNext()) {
String name = types.next();
tm.add(new Template(name, config.getJSONArray(name)));
}

Json with array transformation based upon position using jolt

Iam new to jolt.
Can you please tell me how can i trasform the below json message with array based upon the position in to the below output json message using jolt.
input message :
[
["20084541", "12020584", "Frohmann Dov", "2017", "2", "75", "T7", "DFZ", "CES", "", "", "0", "90", "2010"],
["20084541", "12020584", "Frohmann Dov", "2017", "3", "21", "T7", "DFZ", "CES", "", "", "0", "90", "2010"],
]
output Message :
[{
"policyReference": "20084541",
"insuredId": "12020584",
"insuredName": "Frohmann Dov",
"uwy": "2017",
"subLOB": "2",
"typeOfRisk": "75",
"aircraftcountryCode": "T7",
"aircraftId": "DFZ",
"manufacturerId": "CES",
"aircraftTypeCode": "",
"aircraftSubTypeCode": "",
"aircraftValueAmt": "0",
"aircraftWorkNo": "90",
"yearBuilt": "2010"
}, {
"policyReference": "20084541",
"insuredId": "12020584",
"insuredName": "Frohmann Dov",
"uwy": "2017",
"subLOB": "2",
"typeOfRisk": "75",
"aircraftcountryCode": "T7",
"aircraftId": "DFZ",
"manufacturerId": "CES",
"aircraftTypeCode": "",
"aircraftSubTypeCode": "",
"aircraftValueAmt": "0",
"aircraftWorkNo": "90",
"yearBuilt": "2010"
}]
Any help appreciated.
Spec
[
{
"operation": "shift",
"spec": {
"*": { // loop thru the outer array
// each item of the outer array, is an array
// match individual array indicies, and then send them to the
// output with the nice name.
"0": "[&1].policyReference",
"1": "[&1].insuredId",
"2": "[&1].insuredName"
// etc
}
}
}
]

Write json strings using java (JSP)

I want to create a json string like below.
"data": [{
"id": "1",
"data": "one",
"color": "008ee4"
},{
"id": "2",
"data": "two",
"color": "008ee4"
}]
So far I have come up with this.
<%
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
outerObject.put("data", outerArray);
System.out.println(outerObject.toString());
%>
And it gives the output like
{"data":[]}
I want to remove those curly brackets and input data inside square brackets. Please help me.
UPDATE
{
type: "line",
renderAt: "chartContainer1",
width: "500",
height: "300",
dataFormat: "json",
"dataSource": {
"chart": {
"caption": "Total Revenues from 2008-2013",
"numberprefix": "$",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"plotbordercolor": "008ee4",
"plotborderthickness": "3",
"showvalues": "0",
"divlinecolor": "CCCCCC",
"showcanvasborder": "0",
"tooltipbgcolor": "00396d",
"tooltipcolor": "FFFFFF",
"tooltipbordercolor": "00396d",
"numdivlines": "2",
"yaxisvaluespadding": "20",
"anchorbgcolor": "008ee4",
"anchorborderthickness": "0",
"showshadow": "0",
"anchorradius": "4",
"chartrightmargin": "25",
"canvasborderalpha": "0",
"showborder": "0"
},
"data": [
{
"label": "2009",
"value": "4400000",
"color": "008ee4"
},
{
"label": "2010",
"value": "4800000",
"color": "008ee4"
},
{
"label": "2011",
"value": "5500000",
"color": "008ee4"
},
{
"label": "2012",
"value": "6700000",
"color": "008ee4",
"anchorradius": "7",
"tooltext": "Historical high"
},
{
"label": "2013",
"value": "4200000",
"color": "008ee4"
}
]
}
}
Above is the main json file. I just want to replace the data part with my data.
Do it like this:
JSONObject outerObject = new JSONObject();
JSONArray outerArray = new JSONArray();
JSONObject innerObject = new JSONObject();
JSONArray innerArray = new JSONArray();
innerObject = new JSONObject();
innerObject.put("label", "1");
innerObject.put("value", "one");
innerObject.put("color", "008ee4");
innerArray.add(innerObject);
outerObject.put("data", innerArray);
System.out.println(outerObject.toString());

json parsing using JSONObject

My data is like this:
{
"region":
["{'price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",
"{'price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",
"{'price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}"
]
}
I am doing like below;
JSONObject jsonObj = new JSONObject(jsonString);
JSONArray regionArray = jsonObj.getJSONArray("region");
How do I get each price..
for (int i = 0; i < regionArray.length(); i++) {
JSONObject item = regionArray.getJSONObject(i);
System.out.println(item.getString("price"));
}
Caused by: com.gemstone.org.json.JSONException: JSONArray[0] is not a JSONObject.
You have an array of Strings, not of JSON objects, so you can't do JSON object methods on it.
In order for your code to work, your JSON would have to look like this:
{
"region": [
{
"price": "119",
"volume": "20000",
"pe": "0",
"eps": "4.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
},
{
"price": "112",
"volume": "20000",
"pe": "0",
"eps": "9.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
},
{
"price": "118",
"volume": "20000",
"pe": "0",
"eps": "1.22",
"week53low": "92",
"week53high": "134.4",
"daylow": "117.2",
"dayhigh": "119.2",
"movingav50day": "115",
"marketcap": "0",
"time": "2015-11-25 05:13:34.996"
}
]
}
I just replaced that automatically in a text editor. You can actually let the numbers out of their "" enclosure if you want.
Have a look at it here: http://www.jsoneditoronline.org/
And here's some info on Json: http://www.json.org/

Categories

Resources