How can I add multiple parameters while posting using Swift - json

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)

Related

How can I PUT data into nested JSON in Angular?

I have this JSON file.
{mood: [ {
"id":"1",
"text": "Annoyed",
"cols": 1,
"rows": 2,
"color": "lightgreen",
"route":"/angry",
"musics": [
{
"id": "0",
"name": "English- Heaven's Peace",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgleopO8DiEdsNKgqYZZSEKF",
"descpription": "Tunes that soothe your pained soul",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "1",
"name": "English- Hell's Fire",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EgmZitRQf1X1iYwWW_nUF44L",
"descpription": "Beats that match the ones of your heart",
"reviews": [
{
"name": "abc",
"rating": 3.5,
"review": "energetic",
"date": ""
}
]
},
{
"id": "2",
"name": "Hindi",
"image": "images/music.png",
"link": "",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "3",
"name": "Punjabi",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3Egnntch2thUO55YqPQgo4Qh7",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 4,
"review": "energetic",
"date": ""
}
]
},
{
"id": "4",
"name": "Mix and Match",
"image": "images/music.png",
"link": "https://www.youtube.com/playlist?list=PLPfXrbtn3EglN5LVTETqH3ipRLfXmY6MB",
"descpription": "",
"reviews": [
{
"name": "abc",
"rating": 5,
"review": "energetic",
"date": ""
}
]
}
]
}]
}`
I have created a service that should update any changes in the moods section.
putMood(mood: Mood): Observable<Mood> {
const httpOptions ={
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.put<Mood>(baseURL + 'moods/' + mood.id, mood, httpOptions)
.pipe(catchError(this.processHTTPMsgService.handleError));
}
And a submit function that should put my newly entered review in the reviews section of my json file under musics section.
onSubmit(){
this.review = this.reviewForm.value;
this.review.date = new Date().toISOString();
this.music.reviews.push(this.review);
this.moodservice.putMood(this.mood)
.subscribe(mood => {
this.mood=mood;
},
errmess => {this.mood = null; this.errMess = <any>errmess;});
}
Using this service and function my review is not uploaded to JSON file. What am I doing wrong?

Firebase: JSON payload not accepted

I'm trying to push JSON from a service in to Firebase, and it's not accepting it.
I cant figure out why. JSONLint validates it as valid.
The error I get is:
error: "Invalid data; couldn't parse JSON object, array, or value."
Here's the JSON payload:
{
"app_id": "e4805b8d5a9f4032b0bb8b6d9c6726b8",
"archived": false,
"attachments": {
"form.xml": {
"content_type": "text/xml",
"length": 4500,
"url": "https://someurl.com/form.xml"
}
},
"build_id": "3c5703e20346462ebcb07a3f36d5fe9b",
"domain": "my-test",
"edited_by_user_id": null,
"edited_on": null,
"form": {
"#type": "data",
"#name": "Beneficiary Registration",
"#uiVersion": "1",
"#version": "1",
"#xmlns": "http://openrosa.org/formdesigner/123456",
"beneficiary_age": {
"beneficiary_age_num": "8",
"beneficiary_exact_age_ind": "N"
},
"beneficiary_gender_cd": "M",
"beneficiary_id": "Hhr-O6I3C5L-J3G1L",
"case": {
"#case_id": "a07972bc-1a34-4c84-90ea-91250639f2a4",
"#date_modified": "2020-03-17T20:57:26.986000Z",
"#user_id": "2275c340c48ac83b6852035b0a15b5d3",
"#xmlns": "http://someurl.org/case/transaction/v2"
},
"case_name": "Hhr-O6I3C5L-J3G1L|joel galager|Katsekera|Katsekera|Mpando|Katsekera|KE",
"existing_beneficiaries": "Jane Doe\n\nJoan Doe",
"existing_beneficiaries_label": "",
"household_information": {
"beneficiary_household_information_display": "",
"beneficiary_location_hierarchy_1": "KE",
"beneficiary_location_hierarchy_1_text": "Kenya",
"beneficiary_location_hierarchy_2": "HF0001",
"beneficiary_location_hierarchy_2_text": "Katsekera",
"beneficiary_location_hierarchy_3": "TA0001",
"beneficiary_location_hierarchy_3_text": "Mpando",
"beneficiary_location_hierarchy_4": "GHV0001",
"beneficiary_location_hierarchy_4_text": "Katsekera",
"beneficiary_location_hierarchy_5": "V0001",
"beneficiary_location_hierarchy_5_text": "Katsekera",
"correct_information": "",
"hh_first_name": "John",
"hh_full_name": "John Doe",
"hh_id_fk": "Hhr-O6I3C5L",
"hh_last_name": "Doe",
"household_information": ""
},
"meta": {
"#xmlns": "http://openrosa.org/jr/xforms",
"appVersion": "Formplayer Version: 2.47",
"app_build_version": 1,
"commcare_version": null,
"deviceID": "Formplayer",
"drift": "0",
"geo_point": null,
"instanceID": "123-321-232",
"timeEnd": "2020-03-17T20:57:26.986000Z",
"timeStart": "2020-03-17T20:57:13.958000Z",
"userID": "2275c340c48ac83b6852035b0a15b5d3",
"username": "some_username"
},
"name_group": {
"beneficiary_first_name": "joel",
"beneficiary_full_name": "joel galager",
"beneficiary_last_name": "galager"
},
"subcase_0": {
"case": {
"#case_id": "2a4bfe27-a5c3-4f3a-8540-5f8ded86db85",
"#date_modified": "2020-03-17T20:57:26.986000Z",
"#user_id": "abc123",
"#xmlns": "http://commcarehq.org/case/transaction/v2",
"create": {
"case_name": "Hhr-O6I3C5L-J3G1L|joel galager|Katsekera|Katsekera|Mpando|Katsekera|KE",
"case_type": "beneficiary_case",
"owner_id": "abc123"
},
"index": {
"parent": {
"#text": "a07972bc-1a34-4c84-90ea-91250639f2a4",
"#case_type": "household_case"
}
},
"update": {
"beneficiary_age_num": "8",
"beneficiary_exact_age_ind": "N",
"beneficiary_first_name": "joel",
"beneficiary_full_name": "joel galager",
"beneficiary_gender_cd": "M",
"beneficiary_id": "Hhr-O6I3C5L-J3G1L",
"beneficiary_last_name": "galager",
"beneficiary_location_hierarchy_1": "KE",
"beneficiary_location_hierarchy_1_text": "Kenya",
"beneficiary_location_hierarchy_2": "HF0001",
"beneficiary_location_hierarchy_2_text": "Katsekera",
"beneficiary_location_hierarchy_3": "TA0001",
"beneficiary_location_hierarchy_3_text": "Mpando",
"beneficiary_location_hierarchy_4": "GHV0001",
"beneficiary_location_hierarchy_4_text": "Katsekera",
"beneficiary_location_hierarchy_5": "V0001",
"beneficiary_location_hierarchy_5_text": "Katsekera",
"hh_id_fk": "Hhr-O6I3C5L"
}
}
}
},
"id": "d547ccea-503c-4c50-b974-38ed564ae78a",
"indexed_on": "2020-03-17T21:01:04.695654",
"initial_processing_complete": true,
"is_phone_submission": true,
"metadata": {
"appVersion": "Formplayer Version: 2.47",
"app_build_version": 1,
"commcare_version": null,
"deviceID": "Formplayer",
"drift": "0",
"geo_point": null,
"instanceID": "01010101",
"location": null,
"timeEnd": "2020-03-17T20:57:26.986000Z",
"timeStart": "2020-03-17T20:57:13.958000Z",
"userID": "2275c340c48ac83b6852035b0a15b5d3",
"username": "myusername"
},
"problem": null,
"received_on": "2020-03-17T20:57:27.179986Z",
"resource_uri": "",
"server_modified_on": "2020-03-17T20:57:27.382548Z",
"type": "data",
"uiversion": "1",
"version": "1"
}
This is probably because of #type inside form.
The # character can't be used in RTDB paths.
See How data is structured from the docs.
Keys cannot contain
.
$
#
[
]
/
ASCII control characters 0-31 or 127

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

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

How to Parse this Json using Gson and get the field I want?

{
"ws_result":
[
{
"token": "",
"norm_token": "",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child":
[
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child":
[
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child": [ ]
},
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child": [ ]
}
]
},
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child":
[
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child": [ ]
}
]
}
]
},
{
"token": "",
"norm_token":"",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "2",
"child": [ ]
},
{
"token": "",
"norm_token": "",
"len": "",
"type": "",
"pos": "",
"prop": "",
"stag": "",
"child": [ ]
}
]
}
Such that some children are empty some is not, and some children contain more children. How do I actually parse this thing and get what I want. I am totally new with Json, and I am trying to use Gson. What I want is to get a value of a token with specific type in the nested Json. Thanks a lot for any help and directions.
I tried use com.google.gson.stream.JsonReader, but ist not working
JsonReader jsonReader = new JsonReader(new StringReader(result));
jsonReader.beginObject();
while(jsonReader.hasNext()){
String field = jsonReader.nextName();
if (field.equals("type")){
System.out.println(jsonReader.nextString());
} else if (field.equals("token")){
System.out.println(jsonReader.nextString());
} else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
Parse your json recursively like this:
http://snipplr.com/view/71742/java-reflection-and-recursive-json-deserializer-using-gson/
private void parse(JsonObject o, PackagingResponse r){
Iterator<Entry<String, JsonElement>> i = o.entrySet().iterator();
while(i.hasNext()){
Entry<String, JsonElement> e = i.next();
JsonElement el = e.getValue();
if(el.isJsonObject())
parse(el.getAsJsonObject(), r);
//......
}
}

parse nested json to backbone collections

I'm just starting with Backbone and I'm running into a problem. I have a nice restful setup. For most of my GET request I receive a single collection of models, but for one I am loading nested relational data, which creates nested JSON.
In Backbone I have the following Models:
App.Models.Sequence = Backbone.Model.extend({});
App.Models.Layer = Backbone.Model.extend({});
App.Models.Item = Backbone.Model.extend({});
and these collections
App.Collections.Sequences = Backbone.Collection.extend({
model: App.Models.Sequence,
url: '/api/sequences/'
});
App.Collections.Layers = Backbone.Collection.extend({
model: App.Models.Layer,
url: '/api/layers'
});
App.Collections.Items = Backbone.Collection.extend({
model: App.Models.Item,
url: '/api/items'
});
I load data as JSON:
[
{
"id": "1",
"project_id": "8",
"name": "Seq1",
"layers": [
{
"id": "1",
"name": "Layer11",
"sequence_id": "1",
"items": [
{
"id": "1000000",
"layer_id": "1",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000001",
"layer_id": "1",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000002",
"layer_id": "1",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000003",
"layer_id": "1",
"itemtype_id": "4",
"position": "0"
}
]
},
{
"id": "2",
"name": "Layer12",
"sequence_id": "1",
"items": [
{
"id": "1000004",
"layer_id": "2",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000005",
"layer_id": "2",
"itemtype_id": "2",
"position": "0"
},
{
"id": "1000006",
"layer_id": "2",
"itemtype_id": "3",
"position": "0"
},
{
"id": "1000007",
"layer_id": "2",
"itemtype_id": "4",
"position": "0"
}
]
},
{
"id": "3",
"name": "Layer13",
"sequence_id": "1",
"items": [
{
"id": "1000008",
"layer_id": "3",
"itemtype_id": "1",
"position": "0"
},
{
"id": "1000009",
"layer_id": "3",
"itemtype_id": "4",
"position": "0"
},
{
"id": "1000010",
"layer_id": "3",
"itemtype_id": "5",
"position": "0"
}
]
}
]
},
{
"id": "2",
"project_id": "8",
"name": "Seq2",
"layers": [
{
"id": "4",
"name": "Layer21",
"sequence_id": "2",
"items": []
},
{
"id": "5",
"name": "Layer22",
"sequence_id": "2",
"items": []
}
]
},
{
"id": "3",
"project_id": "8",
"name": "Seq3",
"layers": [
{
"id": "6",
"name": "Layer31",
"sequence_id": "3",
"items": []
},
{
"id": "7",
"name": "Layer32",
"sequence_id": "3",
"items": []
}
]
}
]
How can I get Sequences, Layers and Items into my collections?
You can use a combination of underscore's flatten and pluck to do this neatly:
var data = { /* your JSON data */ };
var allSequences = _.clone(data);
var allLayers = _.flatten(_.pluck(allSequences, 'layers'));
var allItems = _.flatten(_.pluck(allLayers, 'items'));
var sequences = new App.Collections.Sequences(allSequences);
var layers = new App.Collections.Layers(allLayers);
var items = new App.Collections.Items(allItems);
If you don't want Sequences and Layers to contain their child objects, override Model.parse to trim them. For example:
App.Models.Sequence = Backbone.Model.extend({
parse: function(attrs) {
delete attrs.layers;
return attrs;
}
});
And initialize/add the collection with the parse:true option:
var sequences = new App.Collections.Sequences(allSequences, {parse:true});
Et cetera.