Convert raw string to JSON format - arrays

Hi I just have a question on how can I convert this API response into json data. I tried using explode but the response seems like separated into array.
StatCode: 11
StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :
Maybe something like this
{
"StatCode": 11,
"StatName": "cancelled",
"OrderID": "OP_AFIFAH_6889",
"Amount": 1.10,
"TranID": 143519171
etc..
}
Thanks

The best way is changing the API to return the JSON object. If you don't have access to the API, I wrote a simple javascript for you which can convert it to the JSON object:
function toJSON(input) {
const lines = input.split('\n')
const result = []
for (let i = 1; i < lines.length; i++) {
if (!lines[i])
continue;
const obj = {}
const currentline = lines[i].split(':')
obj[currentline[0]] = currentline[1]
result.push(obj)
}
return JSON.stringify(result)
}
console.log(toJSON(`StatName: cancelled
OrderID: OP_AFIFAH_6889
Amount: 1.10
TranID: 143519171
Domain: test
BillingDate: 2019-11-26 16:58:49
BillingName: test
VrfKey: test
Channel: credit
Currency: MYR
ErrorCode: CC_000
ErrorDesc: Successful Payment :`)
);

[
{
"StatName": "cancelled",
"OrderID": "OP_AFIFAH_6889",
"Amount": 1.10,
"TranID": 143519171,
"Domain": "test",
"BillingDate": "2019-11-26 16:58:49",
"BillingName": "test",
"VrfKey": "test",
"Channel": "credit",
"Currency": "MYR",
"ErrorCode": "CC_000",
"ErrorDesc": "Successful Payment"
}
]
Note: Amount and TranID values are both numbers ,if you want them to be a type of string kindly add double quotes to them.
Thanks

Related

Problem with left join with contition typeorm

This is my code:
const query = this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
);
And this is data I got from query:
"requests":
[
{
"id": "8ceee413-521c-4e21-a75b-27048d184804",
"status": "waiting",
"reason": "1",
"approvers": [
{
"id": "04946109-ba35-4c08-a469-761023f33b3c",
"employeeCode": "EMP001",
"status": "waiting",
},
{
"id": "a9dec055-e237-434c-897e-d877f64df4af",
"employeeCode": "EMP002",
"status": "approved",
}
]
}
]
The problem is that when I add contidion to get all request which have been approve by employee EMP002
query.andWhere(`approvers.employeeCode = 'EMP002'`)
The approvers[0] is missing. I know that's correct but I wonder if there is a way to get full approvers but still get requests which have EMP002 is a approver. Thank you for your attention.
You can do this using two queries. First, get all the ids of the request where approvers.employeeCode = 'EMP002'. Then get all the requests where id of request equals the requestIds fetched above.
const results = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.select('request.id', 'id')
.where('approvers.employeeCode = :empCode', { empCode: 'EMP002' })
.getRawMany();
const requestIds = results.map(e => e.id);
const requests = await this.requestRepository
.createQueryBuilder('request')
.leftJoinAndMapMany(
'request.approvers',
RequestApprover,
'approvers',
'request.id = approvers.requestId',
)
.where('request.id IN (:...requestIds)', { requestIds: requestIds });
requests would now contain the desired result.

Kotlin Gson parsing Json Object and Array

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})
}

How to parse JSON response which contains nested JSON array

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?

Flutter : How to get value in Object JSON?

Good healty everyone, I want to ask something about managing data from JSON. I've JSON format like below :
{
"msg": "Success"
"data": [
{
"id": "1",
"notelp": "0000000000",
"user": "no1"
},
{
"id": "2",
"notelp": "1111111111",
"user": "no2"
},
],}
and I want to get value from variable "notelp", I expect output like this {"0000000000", "1111111111",} how to get it ?
I tried this before, but still can't get what I want,
if (response.statusCode == 200) {
final result = json.decode(response.body);
debugPrint('dataTelp: ${result['data']['notelp']}');
}
thank you guys to help me to solve it and stay save.
You can use the forEach or another looping method to get data from a list.
List outPut = [];
List data = response['data'];
data.forEach((element) {
outPut.add(element['notelp']);
});
print(outPut);

How to read objects and store into array

I made an http request and got back e.g the below json. I want to read the cars and the shoes objects into separate arrays at the time of the http request.
json
{
"id": 9,
"name": "Zlatan",
"cars": [
{
"type": "ford",
"year": "2019"
},
{
"type": "audi",
"year": "2017"
}
]
"shoes": [
{
"brand": "adidas",
"status": "old"
},
{
"brand": "timberland",
"status": "new"
}
]
}
comp.ts
cars = [];
shoes = [];
//......
getZlatan() {
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars ....//what to add here
this.shoes ....// here too.
} );
}
Or is there a cleaner way to load the arrays at http request?
Access the cars and shoes properties of the data with simple dot-notation. It might be ideal to check if the data returned is not null with if(condition here) and then perform your logic. If you have more objects and want to bring all cars and shoes under one array then you have to loop through.
getZlatan() {
return this.httpService.getInfo()
.subscribe(data => {
this.objZlatan = data;
this.cars = this.objZlatan.cars;
this.shoes = this.objZlatan.shoes;
});
}
Just use . and type names to access cars and shoes. Let me show an example:
return this.httpService.getInfo()
.subscribe( data => {
this.objZlatan = data; //this part holds the json obj above
this.cars = data.cars;
this.shoes =data.shoes;
} );

Resources