How to map Nested Array of Objects using Swift Object Mapper? - json

I am trying to map an array of objects using Object Mapper
I have this code so far, and my mapping is not successful
do {
if let data = data, let sectorData = Mapper<SubSectorsModel>().mapArrayOfArrays(JSONObject: try JSONSerialization.data(withJSONObject: data, options: [])) {
completionHandler(sectorData,(response as! HTTPURLResponse), error)
print("SectionData Received Successfully")
}
} catch {
completionHandler(nil,(response as! HTTPURLResponse), error)
print("Error parsing json get sector data: ", error.localizedDescription)
}
My Json data is as follows:
[
{
"SECTOR_NAME": "MANUFACTURERS",
"ID": "8",
"SECTOR": [
{
"ID": "144",
"NAME": "Biomass Processing"
},
{
"ID": "8",
"NAME": "Servicing engines and motors"
},
{
"ID": "23",
"NAME": "Furniture & fittings"
},
{
"ID": "31",
"NAME": "Fabrics & textiles"
},
{
"ID": "20",
"NAME": "Hand and machine tools"
},
{
"ID": "28",
"NAME": "Safety and security products"
},
{
"ID": "147",
"NAME": "Jewellery"
},
{
"ID": "156",
"NAME": "Beverages"
},
{
"ID": "165",
"NAME": "Stationery"
},
{
"ID": "9",
"NAME": "Industrial equipment"
},
{
"ID": "25",
"NAME": "Cleaning equipment"
},
{
"ID": "33",
"NAME": "Household consumer products"
},
{
"ID": "162",
"NAME": "Paper Products"
},
{
"ID": "170",
"NAME": "Memoribilia"
},
{
"ID": "143",
"NAME": "Food Products"
},
{
"ID": "22",
"NAME": "Automotive aviation marine and rail products"
},
{
"ID": "30",
"NAME": "Household appliances"
},
{
"ID": "151",
"NAME": "Iron Sheet"
},
{
"ID": "167",
"NAME": "Cosmetics"
},
{
"ID": "11",
"NAME": "Fuel Lubricants & Detergents"
},
{
"ID": "19",
"NAME": "Electrical appliances and equipment"
},
{
"ID": "27",
"NAME": "Packaging products"
},
{
"ID": "7",
"NAME": "Engines & parts"
},
{
"ID": "24",
"NAME": "Glass products"
},
{
"ID": "32",
"NAME": "Clothing & footwear"
},
{
"ID": "152",
"NAME": "Building Material"
},
{
"ID": "142",
"NAME": "Food Processing and Packaging"
},
{
"ID": "21",
"NAME": "Plastic products"
},
{
"ID": "29",
"NAME": "Pool & garden products"
},
{
"ID": "157",
"NAME": "Steel Products"
},
{
"ID": "138",
"NAME": "Optical Prescription Lenses"
},
{
"ID": "10",
"NAME": "Servicing & refurbishing"
},
{
"ID": "18",
"NAME": "Chemical"
},
{
"ID": "26",
"NAME": "Board paper and"
}
]
},
.
.
.
]

If you just want to send completionHandler anyway, use code below:
struct MyJsonStruct : Decodable {
struct SectorStruct : Decodable {
var ID : String
var NAME : String
}
var SECTOR_NAME : String
var ID : String
var SECTOR : [SectorStruct]
}
func handle(_ data : Data ) {
do {
let sectorData = try JSONDecoder().decode(MyJsonStruct.self, from: data) as MyJsonStruct
let yourArray = sectorData.SECTOR // if you need an array result
completionHandler(sectorData,(response as! HTTPURLResponse), error)
print("SectionData Received Successfully")
} catch {
completionHandler(nil,(response as! HTTPURLResponse), error)
print("Error parsing json get sector data: ", error.localizedDescription)
}
}

Related

Unable to parse Service-Now JSON Data

I am new to Python/Scala. Trying to read/parse a JSON file from dataLake using Python and Scala but unsuccessful. Is there something wrong with the .JSON schema. I have attached the JSON schema and the data frame screenshots. Any help would be highly appreciated.
{
"result": [
{
"instance": {
"link": "https://service-now.com/api/now/table/assessment_instance/3d2a2c44d720058ba859e03d2",
"value": "3d2a2c44d720058ba859e03d2"
},
"string_value": "Very Good",
"assign_to_order": "",
"instance_question": {
"link": "https://service-now.com/api/now/table/assessment_instance_question/022a2c44d720058ba859e03d7",
"value": "022a2c44d720058ba859e03d7"
},
"template_definition": "",
"metric_definition": {
"link": "https://service-now.com/api/now/table/metric_definition/7758eb387233200dbba82cb0bfb",
"value": "7758eb387233200dbba82cb0bfb"
},
"sys_updated_on": "207-07-0 02:3:3",
"scaled_value": "4",
"metric": {
"link": "https://service-now.com/api/now/table/metric/542a2c44d720058ba859e03a4",
"value": "542a2c44d720058ba859e03a4"
},
"sys_created_on": "203-2-04 2:34:08",
"sys_domain": {
"link": "https://service-now.com/api/now/table/sys_user_group/global",
"value": "global"
},
"weighted_value": "0.8",
"source_id": {
"link": "https://service-now.com/api/now/table/type/502a2c44d720",
"value": "502a2c44d720058ba859e03a3"
},
"normalized_value": ".33",
"source_table": "metric_type",
"user": "",
"sys_created_by": "admin"
}
]
}
val asmt_metric_result = spark.read.option("multiline", "true")
.json(s"c:/servicenow/asmt_metric_result/2021/09/28/08/32/asmt_metric_result_000000.json")
asmt_metric_result.show(false)

Invalid Json to valid json

How to convert below json to valid json
{
"attribute_id":"r2d2",
"attribute_values":[
WrappedArray( [
5 b1ed5df4a0330a13a3b6f4c,
{
"L0":{
"name":"ENTERTAINMENT",
"id":"20000"
},
"L1":{
"name":"VIDEO GAMES BOOKS AND OTHER MEDIA",
"id":"26000"
},
"L2":{
"name":"MEDIA",
"id":"26001"
},
"L3":{
"name":"BOOKS",
"id":"26100"
},
"L4":{
"name":"BOOKS MISC L4",
"id":"26800"
}
},
PRIORITY_OTHERS,
1536662873016,
26800
] )
],
"bu":"0",
"item_id":"705024754",
"last_updated_by":"QARTH",
"mart":"0",
"published_at":"1536662873017",
"source":"RAMP",
"timestamp":"1536662873016",
"vertical":"0",
"wpid":"7HX1KF1N9W9Y"
}
Valid json should be this
{
"attribute_id": "r2d2",
"attribute_values": [
[{
"L0": {
"name": "ENTERTAINMENT",
"id": "20000"
},
"L1": {
"name": "VIDEO GAMES BOOKS AND OTHER MEDIA",
"id": "26000"
},
"L2": {
"name": "MEDIA",
"id": "26001"
},
"L3": {
"name": "BOOKS",
"id": "26100"
},
"L4": {
"name": "BOOKS MISC L4",
"id": "26800"
}
},
"PRIORITY_OTHERS",
1536662873016,
26800
]
],
"bu": "0",
"item_id": "705024754",
"last_updated_by": "QARTH",
"mart": "0",
"published_at": "1536662873017",
"source": "RAMP",
"timestamp": "1536662873016",
"vertical": "0",
"wpid": "7HX1KF1N9W9Y"
}
Could you please post your sql if this does not answer your question?

How to Access JSON Object contains json in Angular 2

I want to show the data name, age, address in Angular2 DataTable or any other grid view controls in Angular2
[{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy",
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai",
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai",
}
}]
}];
Considering your question json as response
this.data = response[0].data;
<li *ngFor="let d of data">
{{d?.name}}
{{d?.age}}
{{d?.Address}}
</li>
In case your first array (json ) has multiple objects and then use nested ngFor
Pojo Classes
export class Data {
name: string;
age: string;
Address: string;
}
export class Datum {
id: string;
data: Data;
}
export class RootObject {
status: number;
message: string;
data: Datum[];
}
In Component.ts
export class AbcComponent implements OnInit {
a: any;
rootObj: RootObject = new RootObject();
constructor() { }
ngOnInit() {
this.a = [{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy",
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai",
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai",
}
}]
}]
this.rootObj = this.a;
console.log(this.rootObj.data[0].data.age)
}
}
In html :-
<table [mfData]="data[0].data" #mf="mfDataTable">
<tbody>
<tr *ngFor="let item of mf.data">
<td>{{item.data.name}}</td>
<td>{{item.data.Address}}</td>
<td>{{item.data.age}}</td>
<td>{{item.city | uppercase}}</td>
</tr>
</tbody>
</table>
In Component.ts :-
`data = [{
"status": 1,
"message": "Records Found",
"data": [{
"id": "1",
"data": {
"name": "Joseph",
"age": "25",
"Address": "Trichy"
}
}, {
"id": "2",
"data": {
"name": "John",
"age": "35",
"Address": "Chennai"
}
}, {
"id": "3",
"data": {
"name": "martin",
"age": "25",
"Address": "Chennai"
}
}]`

Grab an ID from particular array index

I have some JSON which returns the following:
"data": [
{
"created_time": "2010-09-03T16:07:14+0000",
"name": "Profile Pictures",
"id": "125287297520173"
},
{
"created_time": "2010-12-03T00:05:31+0000",
"name": "Mobile Uploads",
"id": "146617845387118"
},
{
"created_time": "2013-07-27T11:34:50+0000",
"name": "Timeline Photos",
"id": "546011742114391"
},
{
"created_time": "2017-01-04T19:02:40+0000",
"name": "Untitled Album",
"id": "1178578645524361"
},
{
"created_time": "2016-09-10T18:26:25+0000",
"name": "Untitled Album",
"id": "1076646985717528"
},
{
"created_time": "2016-07-06T18:27:09+0000",
"name": "OS X Photos",
"id": "1033031426745751"
},
{
"created_time": "2013-06-22T07:32:01+0000",
"name": "iOS Photos",
"id": "530462737002625"
},
{
"created_time": "2012-05-22T19:01:42+0000",
"name": "Cover Photos",
"id": "370987619616805"
},
{
"created_time": "2015-08-27T18:59:56+0000",
"name": "Untitled Album",
"id": "879780692070826"
},
{
"created_time": "2014-12-06T16:13:01+0000",
"name": "DRMC 2005 Batch",
"id": "761469943901902"
},
{
"created_time": "2013-06-16T09:01:17+0000",
"name": "Instagram Photos",
"id": "528368577212041"
},
{
"created_time": "2012-09-09T17:37:55+0000",
"name": "Liverpool Exclusive",
"id": "416230538425846"
},
{
"created_time": "2012-09-10T16:31:52+0000",
"name": "LIVERPOOL FC TOUR",
"id": "416540875061479"
},
{
"created_time": "2010-06-11T19:37:20+0000",
"name": "cars",
"id": "104577376257832"
},
{
"created_time": "2011-03-29T23:50:18+0000",
"name": "Camera+ Photos",
"id": "174268382622064"
}
]
I would like to grab the id of the field "name": "Profile Pictures" . I am using SwiftyJSON to cast the types and so far I managed to do this :
let dictionary = JSON(result)
// print("albums **************\(dictionary)")
if let data = dictionary["data"].array {
print("data of profilePicture ******* \(data)")
let index = data.index{ $0["name"] == "Profile Pictures" }
}
}
I could detech the name of profilePicture as you can see but now I want to grab the id of that json object. Please help.
Use filter to get the dictionary you're interested in…
let dictionary = JSON(result)
// print("albums **************\(dictionary)")
if let data = dictionary["data"].array {
print("data of profilePicture ******* \(data)")
if let dict = data.filter{ $0["name"] == "Profile Pictures" }.first as? [String: String] {
let id = dict["id"]
}
}
let dictionary = JSON(result)
// print("albums ID are **************\(dictionary)")
if let data = dictionary["data"].array {
print("data of profilePicture ******* \(data)")
if let dict = data.first(where: { ($0["name"].string ) == "Profile Pictures" }) {
let id = dict["id"]
print("my desired id : ********* \(id)")
}
}

How can I add multiple parameters while posting using Swift

I have the following multiple json objects to post data using Alamofire. In which format I need to pass the parameters in swift. I am new to swift . Help me out.
{
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
"sandage": {
"bank": "",
"bag": ""
},
"inst": "",
"items": [{
"itemid": "606",
"qty": "1",
"sub": [{
"item": "1586",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1588",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1589",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1590",
"qty": "1",
"type": "addon",
"ext": ""
}]
}, {
"itemid": "639",
"qty": "1",
"sub": [{
"item": "1618",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1612",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1611",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1610",
"qty": "1",
"type": "addon",
"ext": ""
}]
}],
"discount": "0",
"coupon": [],
"delivery": "",
"user": {
"id": "13",
"fname": "Demo",
"lname": "Order",
"phone": "9876543210",
"dno": "",
"add1": "",
"add2": "",
"postcode": "",
"username": "demo#theepos.com",
"status": "1"
},
"otype": "1",
"ptype": "0",
"app_id": "A1A2A3A4",
"app_key": "K1K2K3K4",
"request": "placeorder"
}
I am using Alamofire to post the data..
var url: NSURL = NSURL(string: "http://\(platform).eposapi.co.uk")!
let params = [
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
.....
]
Alamofire.request(.POST, url, parameters: params, encoding: .JSON)
.responseJSON{ response in
if let result: AnyObject = response.result.value
{
let post: JSON = JSON(result)
}
}
Really thanks guys . I only followed the above commented instructions and got the answer. Help really appreciated
var url: NSURL = NSURL(string: "http://\(platform).eposapi.co.uk")!
let sandage = ["bank": "","bag": ""]
let sub_array = [ "item": "1586","qty": "1","type": "addon","ext": ""]
let items_array = ["itemid": "606","qty": "1","sub": sub_array ]
let user_Detail = ["id": "13","fname": "Demo","lname": "Order",
"phone": "9876543210","dno": "","add1": "",
"add2": "","postcode": "","username": "demo#theepos.com",
"status": "1"]
let params = [
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
"sandage": sandage,
"inst": "",
"items":items_array,
"discount": "0",
"coupon": [],
"delivery": "",
"user": user_Detail,
"otype": "1",
"ptype": "0",
"app_id": "A1A2A3A4",
"app_key": "K1K2K3K4",
"request": "placeorder"
]
Alamofire.request(.POST, url, parameters: params, encoding: .JSON)
.responseJSON{ response in
if let result: AnyObject = response.result.value
{
let post: JSON = JSON(result)
let status = post["status"].stringValue
let order_id = post["order_id"].stringValue
print(status)
print(order_id)