I have a query, I have to read key "class" under key"studentData" from the below mentioned json response.
{
"studentData": [
{
"name": "john",
"class": 2,
"rollno": "2015"
}
],
"yearofenrollment": 2017
}
Please help.
Thanks in advance
JSONObject jsonObjectResponse = new JSONObject(response.toString()); //obtain the object
JSONArray jsonMainNode = jsonObjectResponse.optJSONArray("studentData");//get array from object
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);//get first object in array
String studentDataValue = jsonChildNode.optString("class");//obtain value from class key
Related
I am pretty new to Kotlin and Json and on my work I use GSON to parse the Json.
I need to parse the following Json file into a Class by using GSON.
{
"apiKey": "blablabla",
"baseUrl": "blablabla",
"requestData": [
{
"lng": "6.971",
"lat": "50.942",
"rad": "1.5",
"type": [
"diesel",
"super"
]
},
{
"lng": "6.442",
"lat": "51.180",
"rad": "1.5",
"type": [
"diesel",
"super"
]
},{
"lng": "7.136",
"lat": "50.991",
"rad": "1.5",
"type": [
"diesel",
"super"
]
}
]
}
Now I tried to make a data class like this:
data class ApiParameterData(
var apiKey: String? = null,
var baseUrl: String? = null,
var requestData: String? = null) {
}
I also made another class to store the Json informations in it like this:
class Tankstelle: JsonDeserializer<ApiParameterData> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?
): ApiParameterData {
json as JsonObject
val apiKey = json.get("apiKey").asString
val baseUrl = json.get("baseUrl").asString
val requestDataJson = json.get("requestData")
val requestData = if (requestDataJson.isJsonObject) requestDataJson.asJsonObject.toString() else requestDataJson.toString()
return ApiParameterData(apiKey, baseUrl, requestData)
}
}
I tried to call it like that:
val gsonConfig = GsonBuilder().registerTypeAdapter(ApiParameterData::class.java, Tankstelle()).create()
val tanke = gsonConfig.fromJson(readJson, ApiParameterData::class.java)
println(tanke.requestData?.get(0))
But of course the output I get is "[" . I think because I get back a String or something and this is the first symbol of it?
I need to loop trough the requestData list and store it as a instance of a class and need to access each different value.
The thing is that I want to give the Json file different places and ranges it should look for gasstations. By reading the Json it should take all the pieces and create a link for each place I write in the requestData list. So in this case I would need 3 different links at the end. But this is another part I can do myself. I just don't know how to parse it so I can access and store every value in this Json.
Thank you already and have a great weekend!
If you need more informations just let me know
First you need to define two types that map to your JSON structure
class ApiParameterData(
val apiKey: String,
val baseUrl: String,
val requestData: List<RequestObject>
)
class RequestObject(
val lng: String,
val lat: String,
val rad: String,
val type: List<String>
)
Now simply parse it as
val apiData = Gson().fromJson(readJson, ApiParameterData::class.java) // No need to add TypeAdapter
// To get requestData
val requestData = apiData.requestData
requestData.forEach {
print("${it.lng}, ${it.lat}, ${it.rad}, ${it.type})
}
I'm trying to parse a JSON response from an API and store the data to DATA CLASS and sending the data to recycler adapter as ArrayList.
The JSON Array has another array of objects inside, and I'm not able to find a way to properly parse that JSON response.
Here is my data class:
data class OrderDetails (
val orderId: String, // order_id value from json object goes here //
val restaurantName: String, // restaurant_name value from json object goes here //
val totalCost: String, // total_cost value from json object goes here //
val orderDate: String, // order_placed_at value from json object goes here //
val orderFoodDetails: String // food_items value in json response is an array and i'm stuck here //
)
Here is my Kotlin code:
try {
val data = it.getJSONObject("data")
val success = data.getBoolean("success")
if (success) {
val arrayData = data.getJSONArray("data")
for (i in 0 until arrayData.length()) {
val orderJsonObject = arrayData.getJSONObject(i)
val orderObject = OrderDetails(
orderJsonObject.getString("order_id"),
orderJsonObject.getString("restaurant_name"),
orderJsonObject.getString("total_cost"),
orderJsonObject.getString("order_placed_at"),
orderJsonObject.getJSONArray("food_items").toString() // getting array and storing as a string
)
orderList.add(orderObject)
for (orders in orderList) {
val foodData = orders.orderFoodDetails
val jsonFood = JSONArray(foodData)
for (j in 0 until jsonFood.length()) {
val foodJsonObject = jsonFood.getJSONObject(j)
val foodObject = OrderFoodDetails(
foodJsonObject.getString("food_item_id"),
foodJsonObject.getString("name"),
foodJsonObject.getString("cost")
)
ordersFood.add(foodObject)
}
}
}
Here is the Json response:
{
"data": {
"success": true,
"data": [
{
"order_id": "17790",
"restaurant_name": "Rotten Tomatoes",
"total_cost": "280",
"order_placed_at": "02-11-20 19:00:54",
"food_items": [
{
"food_item_id": "156",
"name": "Rotten Bhajiya",
"cost": "100"
},
{
"food_item_id": "155",
"name": "Rotten Salad",
"cost": "100"
},
{
"food_item_id": "154",
"name": "Rotten Soup",
"cost": "80"
}
]
},
Required Output
Prefered Output
My output
my current output
do you tried to use GSON or Moshy lib ?
This case will be easier solved with one of this :)
If you don't want to use one of them, just try to replace your for cycle to map or for each, to make it more readable. Looks like you make it right, but can you check the result of try catch block please?
I have a problem with the construction of a Json for Amazon Kinesis.
This json has to have this format:
{
"Records": [
{
"Data": "XzxkYXRhPl8x",
"PartitionKey": "partitionKey1"
},
{
"Data": "f1PxFQo92Afh",
"PartitionKey": "partitionKey2"
},
{
"Data": "Gi4sEdd08HypA",
"PartitionKey": "partitionKey3"
}
],
"StreamName": "exampleStreamName"
}
I use an BeanShell Sampler to create the json as a buffer:
import org.json.JSONArray;
import org.json.JSONObject;
//Dichiarazione variabili
int timestampValue=(${startTime}+${i}+1);
float current_powerValue=${current_power_1}+${__Random(0,10)};
String idValue=${__threadNum}+"_"+"5";
JSONObject part = new JSONObject();
//Create JSON
part.put("timestamp",timestampValue);
part.put("parent","${__threadNum}");
part.put("id",idValue);
part.put("state","on");
part.put("today_kwh",65);
part.put("current_power",current_powerValue);
part.put("today_on_time",0);
part.put("on_for",0);
part.put("today_standby_time",0);
//ADD json to array
if(${i}%(${bufferSize}*${sample}-1)==0 && ${i}!=0 || ${i}==${totalNumber}-${endOfDb}){
//Add to json variable the last json created
vars.put("json",vars.get("json")+part.toString());
//Make an JSONObject by json variable of jmeter
JSONObject tempArray= new JSONObject(vars.get("json"));
log.info(tempArray.toString());
//Add tempArray into JSONArray so that it adds square brackets
JSONArray records= new JSONArray();
records.put(tempArray);
//Add the second field streamName
JSONObject kinesis = new JSONObject();
kinesis.put("records",records);
kinesis.put("streamName","kinesis");
//save into jsonBuffer
vars.put("jsonBuffer",kinesis.toString());
//restart json variable
vars.put("json","");
}
else{
//add new json into variable so to store it.
vars.put("json", vars.get("json")+part.toString()+",");
}
I use json variable in jmeter to save the json for each iteraction and when the "i" variable respect the if clause then I start to create the json structure.
So I add the last json to the jmeter variable, then I create a JSONObject to store this json but when i do this it store only one json (because it is an object).
Unfortunately if I store in a JSONArray it add "" because read the variable json as a string.
The best solution would be use only JSONObject and JSONArray but how I use the same object for all the iteractions(in jmeter i can't use JSONArray)
This is my jmx
You could trt with this snippet:
if(${i}%(${bufferSize}*${sample}-1)==0 && ${i}!=0 || ${i}==${totalNumber}-${endOfDb}){
vars.put("json",vars.get("json")+part.toString());
JSONArray records= new JSONArray("["+vars.get("json")+"]");
log.info(records.toString());
//records.put(tempArray);
JSONObject kinesis = new JSONObject();
kinesis.put("records",records);
kinesis.put("streamName","kinesis");
vars.put("jsonBuffer",kinesis.toString());
vars.put("json","");
}
Im trying to compare two specific bits of information. One is in the form of a as3 string the other is in the form of a Json array.
The Json array shows customer data from a shop website. What i want to do is have as3 compare the string(i.e a customer name) with the data , and when it has found the matching name, only trace that customers specific information.
Im amusing id have to use a loop for the comparison , but im having trouble getting my head around how to convert the Json into specific junks that can then be compared individually with a string. Any help would be perfect.
Thanks
Be aware that JSON is just a standard AS3 object. There's no magic going on here; loop through it as you would any other structure and run your comparisons as usual.
Solution
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
var myString:String = "fake name";
for (var k:String in jsonObj.customers[0]) {
var v:String = jsonObj.customers[0][k];
if (v == myString) {
trace(myString + "'s email is " + jsonObj.customers[0].email)
}
}
Use a Dictionary Object to store customer objects using their unique names (or ids ) as reference;
You certainly do not want to write unnecessary loop search for a customer in question.
Solution.
var jsonObj:Object = {
"customers": [
{
"id": "04aa1ab3-521b-11e3-a29a-bc305bf5da20",
"name": "fake name",
"customer_code": "00000002",
"customer_group_id": "6012cd22-5166-11e3-a29a-bc305bf5da20",
"customer_group_name": "All Customers",
"first_name": "test",
"last_name": "test",
"company_name": "",
"email": "testest#yahoo.com"
}
]
}
//Dictionary Object to store customers
var customers:Dictionary=new Dictionary();
//customer object in the json
var customer:Object;
//loop json object to retrieve customers and
//store them in Dictionary using either unique name or id
for each(customer in jsonObj)
customers[customer.name]=customer;
//retrieve customer in question
function getCustomer(id:String):Object
{
return customers[id] as Object;
}
I have a json response coming in from a php file, the json response looks as below results:
[
{
"header": "Client ID",
"dataindex": "clientID"
},
{
"header": "Client Name",
"dataindex": "clientName"
},
{
"header": "Progress Bar",
"dataindex": "progressBar"
}
]
Now I want to copy this data into an array in the following way
var allColumns = [];
//loop through the json response
var singleColumn = [];
singleColumn['header'] = Client ID from the json response whose key is header
singleColumn[dataindex'] = clientID from the json response whose key is header.
Please note: I need to do this is extjs3.
If I am getting you correctly you are getting the JSON as a string from an ajax call to your PHP handler in a string format and you want to cast it into a Javascript array of coloumn objects.
you can do it like this:
var allColumns = Ext.decode(YOUR PHP JSON FORMATTED RESULT);
this will allow you to iterate over the result set as an in memory javascript array of objects like this:
for(var i=0 ; i < allColumns.length; i++){
allColumns[i].header ...
allColumns[i].dataindex ...
}
I hope I got you right...