how to post manually created json object in ios - ios

Please help me. I want to post this json data which I created manually. And I'm getting error as Object reference not set to an instance of an object.
{
customerId = 81;
lstOrderItems = (
{
itemId = 149;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 135;
lstOrderAttributeValue = (
{
attributeValueId = 173;
},
{
attributeValueId = 174;
}
);
}
);
},
{
itemId = 129;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = (
{
attributeId = 119;
lstOrderAttributeValue = (
{
attributeValueId = 143;
},
{
attributeValueId = 144;
},
{
attributeValueId = 145;
},
{
attributeValueId = 155;
}
);
},
{
attributeId = 120;
lstOrderAttributeValue = (
{
attributeValueId = 146;
},
{
attributeValueId = 147;
}
);
},
{
attributeId = 124;
lstOrderAttributeValue = (
{
attributeValueId = 158;
},
{
attributeValueId = 165;
}
);
}
);
},
{
itemId = 132;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
},
{
itemId = 144;
itemQnt = 1;
itemTotalPrice = 205;
lstOrderAttribute = ( );
}
);
orderTotalPrice = 291;
outletId = 54;
}

To make your life a bit easier i won't suggest you to construct a json on your own, instead make a dictionary (or array, as per the need) and pass it to json serializer, it will construct a valid json for you (if possible).
Sample code:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:userFirstName, #"fname", userLastName, #"lname", nil];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted error:&error];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"json : %#", json);
Output log:
2014-03-18 12:03:19.393 DesignMantic[1351:70b] json : {
fname = John;
lname = Doe;
}
Pass the constructed json to your service and you are free to invalid json issues.
Reference:
how to create json in objective-c
Hope it helps!
EDIT
Possibly, the data is not serialized to a valid json (may be because it is not convertable to json) and returned nil. You should check it first if the data is converted to json or not rty like this:
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:infoDictionary options:NSJSONWritingPrettyPrinted error:&error];
if(jsonData && [NSJSONSerialization isValidJSONObject:jsonData])
{
NSString *postString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *url = [NSString stringWithFormat:#"sqwip.ignivainfotech.net/api/customerapi/…"];
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:url]];
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
// Through error, since data sent for JSON serialisation is not convertible to json format
}

Your JSON Format is inValid
JSON Syntax Rules
JSON syntax is a subset of the JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
you must have your Format like below one
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.64,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
}

JSONLint is a great way to find out what's wrong with hand-coded JSON.  There are both command-line and web-based versions.
If you were to paste the above JSON into JSONLint.com, you would see that one of the first mistakes you're making is using hash keys that aren't strings.  Fix that, and there may be other errors you'll need to correct.
You'll learn the restrictions of JSON gradually and iteratively using a lint program like this.  Good luck.

Related

How to convert following string to JSON?

Hello guys i am facing problem related to convert string to json.
Here is my String :
[
{
"SCHEME_NAME": "FUG RSA SCHEME",
"Investment_Value": -46719.00201558,
"Bid_Price": 2.2566,
"Total_Contributions": 0,
"Growth": -46719.00201558,
"INVESTOR_ID": 5613,
"PFA_SCHEMEID": 1
},
{
"MONTH_NAME": "Balance as at 07-07-2016",
"EMPLOYEE_CONTRIBUTION": 3433764.77,
"EMPLOYER_CONTRIBUTION": 4381387.29,
"TOTAL_VALUE": 7815152.06,
"TOTAL_UNITS": 2782788.3885,
"TOTAL_FEE": 0,
"TOTAL_CONTRIBUTION": 7815152.06,
"Voluntary": "0.00"
},
{
"MONTH_NAME": "July 2016",
"EMPLOYEE_CONTRIBUTION": 0,
"EMPLOYER_CONTRIBUTION": 0,
"TOTAL_VALUE": 0,
"TOTAL_UNITS": -20703.2713,
"TOTAL_FEE": 0,
"TOTAL_CONTRIBUTION": 0,
"Voluntary": "0.00"
}
]
How to convert it into JSON?
Please help me.
Try this:
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:&error];
JSON is nothing but pairs of key/value pairs enclosed with an enclosed {} braces but you're missing one. You need one more enclosing root {} curly braces and specify key for your array, currently I've specified response, as per your requirement, then the JSON is valid.
{
"response": [
...
]
}
and then you can convert it with what #SaintThread has mentioned.
It is already in JSON format.I tried to convert string to json.I got it.But the result is same as what it is in question.
When convert string to json it should be in \"Key\":\"Value\" or \"Key\":Value
NSString *str=#"[{\"SCHEME_NAME\":\"FUG RSA SCHEME\",\"Investment_Value\":-46719.00201558,\"Bid_Price\":2.2566,\"Bid_Price\":\"2.2566\",\"Total_Contributions\":0,\"Growth\":-46719.00201558,\"INVESTOR_ID\":5613,\"PFA_SCHEMEID\":1},{ \"MONTH_NAME\": \"Balance as at 07-07-2016\",\"EMPLOYEE_CONTRIBUTION\": 3433764.77,\"EMPLOYER_CONTRIBUTION\": 4381387.29,\"TOTAL_VALUE\": 7815152.06,\"TOTAL_UNITS\": 2782788.3885,\"TOTAL_FEE\": 0,\"TOTAL_CONTRIBUTION\": 7815152.06,\"Voluntary\": \"0.00\"},{\"MONTH_NAME\": \"July 2016\",\"EMPLOYEE_CONTRIBUTION\": 0,\"EMPLOYER_CONTRIBUTION\":0,\"TOTAL_VALUE\":0,\"TOTAL_UNITS\": -20703.2713,\"TOTAL_FEE\": 0,\"TOTAL_CONTRIBUTION\": 0,\"Voluntary\": \"0.00\"}]";
NSData *dataStr = [str dataUsingEncoding:NSUTF8StringEncoding];
id jsonData = [NSJSONSerialization JSONObjectWithData:dataStr options:0 error:nil];
NSLog(#"The converted string to json is %#",jsonData);
Now the Printed result is
The converted string to json is (
{
"Bid_Price" = "2.2566";
Growth = "-46719.00201558";
"INVESTOR_ID" = 5613;
"Investment_Value" = "-46719.00201558";
"PFA_SCHEMEID" = 1;
"SCHEME_NAME" = "FUG RSA SCHEME";
"Total_Contributions" = 0;
},
{
"EMPLOYEE_CONTRIBUTION" = "3433764.77";
"EMPLOYER_CONTRIBUTION" = "4381387.29";
"MONTH_NAME" = "Balance as at 07-07-2016";
"TOTAL_CONTRIBUTION" = "7815152.06";
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "2782788.3885";
"TOTAL_VALUE" = "7815152.06";
Voluntary = "0.00";
},
{
"EMPLOYEE_CONTRIBUTION" = 0;
"EMPLOYER_CONTRIBUTION" = 0;
"MONTH_NAME" = "July 2016";
"TOTAL_CONTRIBUTION" = 0;
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "-20703.2713";
"TOTAL_VALUE" = 0;
Voluntary = "0.00";
}
)
Then When I get the data into array
NSArray *arrJson = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
NSLog(#"The arrjson is %#",arrJson);
The printed result is
The arrjson is (
{
"Bid_Price" = "2.2566";
Growth = "-46719.00201558";
"INVESTOR_ID" = 5613;
"Investment_Value" = "-46719.00201558";
"PFA_SCHEMEID" = 1;
"SCHEME_NAME" = "FUG RSA SCHEME";
"Total_Contributions" = 0;
},
{
"EMPLOYEE_CONTRIBUTION" = "3433764.77";
"EMPLOYER_CONTRIBUTION" = "4381387.29";
"MONTH_NAME" = "Balance as at 07-07-2016";
"TOTAL_CONTRIBUTION" = "7815152.06";
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "2782788.3885";
"TOTAL_VALUE" = "7815152.06";
Voluntary = "0.00";
},
{
"EMPLOYEE_CONTRIBUTION" = 0;
"EMPLOYER_CONTRIBUTION" = 0;
"MONTH_NAME" = "July 2016";
"TOTAL_CONTRIBUTION" = 0;
"TOTAL_FEE" = 0;
"TOTAL_UNITS" = "-20703.2713";
"TOTAL_VALUE" = 0;
Voluntary = "0.00";
}
)
Converting NSString to JSON
datasting to json
try this online json viewer:
http://jsonviewer.stack.hu/
You can format and view it online
Here is a format
[
{
"SCHEME_NAME": "FUG RSA SCHEME",
"Investment_Value": -46719.00201558,
"Bid_Price": 2.2566,
"Total_Contributions": 0.00,
"Growth": -46719.00201558,
"INVESTOR_ID": 5613,
"PFA_SCHEMEID": 1
}
,
{
"MONTH_NAME": "Balance as at 07-07-2016",
"EMPLOYEE_CONTRIBUTION": 3433764.77,
"EMPLOYER_CONTRIBUTION": 4381387.29,
"TOTAL_VALUE": 7815152.06,
"TOTAL_UNITS": 2782788.3885,
"TOTAL_FEE": 0.00,
"TOTAL_CONTRIBUTION": 7815152.06,
"Voluntary": "0.00"
},
{
"MONTH_NAME": "July 2016",
"EMPLOYEE_CONTRIBUTION": 0.00,
"EMPLOYER_CONTRIBUTION": 0.00,
"TOTAL_VALUE": 0.00,
"TOTAL_UNITS": -20703.2713,
"TOTAL_FEE": 0.00,
"TOTAL_CONTRIBUTION": 0.00,
"Voluntary": "0.00"
}
]

How to parse Dynamic changes in json value. Dictionary with 2 nested dic & then array and then dic again

Dictionary with two nested dictionary and then array and then dictionary again how can i write code generally for objective c ,iOS 8;
{
"brands": {
"Clinique": {
"Foundation": {
"Even Better Makeup SPF 15": {
"productName": "Even Better Makeup SPF 15",
"colors": [
{
"id": "30816",
"client_id": "1422956000sjdaC",
"product_id": "190",
"shade_name": "Alabaster",
"shade_code": "#F0C9AE",
"color_id": null,
"image_url": "",
"price": "",
"offer": "",
"created_by": "1422956000sjdaC",
"created_date": "2015-03-06",
"sku_id": "",
"product_web_url": "",
"brand_id": "Clinique",
"product_name": "Even Better Makeup SPF 15",
"makeup_type": "Foundation",
"color_family": "cool"
},
As I can see, your JSON response is sending Product details, so the
"brands": {
"Clinique": {
"Foundation": {
will remain same always, and the response below it will change according to products.
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *productsDict = [[jsonDictionary objectForKey:#"brands"] objectForKey:#"Clinique"] objectForKey:#"Foundation"];
NSArray *keys=[productsDict allKeys];
for (int i = 0; i < keys.count; i++) {
NSDictionary *prodSingle = [productsDict objectForKey:[NSString StringWithFormat:#"%#",keys[i]]];
}
Now you have prodSingle, use this to get data of each product.
Note: Untested, I'll provide a tested version if this doesn't work.
EDIT:
As you said only brands key will remain constant and other will change dynamically,
you should do this :
So what you can do is create a NSDictionary with jsonData(response data) like this:
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
create a dictionary of brands
NSDictionary *brandsDict = [jsonDictionary objectForKey:#"brands"];
Now get all the keys:
NSArray *keys= [brandsDict allKeys];
Now use each key you got in Array to fetch data accordingly.

JSON Parsing Issue

Hello I am new to iOS development. I am trying to parse a JSON response. Below is the top part of the response:
Table =
{
Rows = {
results = (
{
Cells = {
results = (
{
Key = Rank;
Value = "6.251145362854";
ValueType = "Edm.Double";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = DocId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" =
{
type = "SP.KeyValue";
};
},
{
Key = WorkId;
Value = 978473;
ValueType = "Edm.Int64";
"__metadata" = {
type = "SP.KeyValue";
};
},
{
Key = Title;
Value = "Vneea Ready!";
ValueType = "Edm.String";
"__metadata" =
{
type = "SP.KeyValue";
};
},.........................
Now I am using
NSError *error;
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"];
So I was able to refine it until here, but then I use
NSDictionary *results = jsonObject[#"Table"][#"Rows"][#"results"][#"Cells"];
When I am going further for Cells and results it is giving me Empty element Error,
After referring to this post JSON parsing using NSJSONSerialization in iOS, it seems like "(" means an array in the response, but it is not working for me. Can someone help me, please?
results is an array, not a dictionary, so you cannot access its contents by name. Your JSON doesn't look well formed, though, because Key should be a string ("Title" not Title).
Each element in the results array is a dictionary, so to get the Value that corresponds to Title you can use
NSArray *results=jsonObject[#"Table"][#"Rows"][#"results"];
NSDictionary *result=[results objectAtIndex:0]; // access the first result
for (NSDictionary *result in results) {
if ([result[#"Key"] isEqualToString:#"Title"]) {
NSLog(#"The value of Title is %#",result[#"Value"]);
break;
}
}

Convert text into json in Objective c

I have a string that I want to convert it into JSON in iOS but it is returning nil when I'm parsing it using jsonkit. My string format is as follows.
[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]
Any one have idea how I can convert into a JSON object? Any help is appreciated.
The problem I would see here is your JSON string is invalid. Validate your JSON here
Try this
NSString *strJson = #"[{\"index\": \"0\",\"title\": \"ARPPU\"}]";
id jsonObj = [NSJSONSerialization JSONObjectWithData:[strJson dataUsingEncoding:NSUTF8StringEncoding]
options:NSJSONReadingMutableContainers error:nil];
This worked for me.
Convert your string to NSData with NSUTF8Encoding and do a JSONSerialisation to make it JSON
// Converting Your String to NSData
NSString *myString=#"[
{ index:0, title:ARPPU },
{ index:1, title:ARPU },
{ index:2, title:Conversion },
{ index:3, title:DAU },
{ index:4, title:DAU },
]";
// Converts the string to Data
NSData* data = [myString dataUsingEncoding:NSUTF8StringEncoding];
// Does JSONSerialisation and convert the data into JSON
NSDictionary*dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// Prints here the JSON
NSLog(#"Dict value==%#",dict);
First fix the JSON string, see Introducing JSON and W3Schools.
Then it is a JSONstring representation.
Convert to NSData and use JSONObjectWithData:options:error:
NSString *JSONStringRepresentation= #"["
#"{ \"index\":0, \"title\":\"ARPPU\" },"
#"{ \"index\":1, \"title\":\"ARPU\" },"
#"{ \"index\":2, \"title\":\"Conversion\" },"
#"{ \"index\":3, \"title\":\"DAU\" },"
#"{ \"index\":4, \"title\":\"DAU\" },"
#"]";
NSData *JSONAsData = [JSONStringRepresentation dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *JSONAsArrayObject = [NSJSONSerialization JSONObjectWithData:JSONAsData options:0 error:&error];
NSLog(#"JSONAsArrayObject: %#", JSONAsArrayObject);
NSLog output:
JSONAsArrayObject: (
{
index = 0;
title = ARPPU;
},
{
index = 1;
title = ARPU;
},
{
index = 2;
title = Conversion;
},
{
index = 3;
title = DAU;
},
{
index = 4;
title = DAU;
} )

JSon parsing error IOS with empty object key

Hi I have this JSON I'm trying to parse using NSDictionary and trying to get the values as mentioned . but the problem is i do not get a key when i further go into the JSON is there any way to remove this key to go more deep.
NSDictionary *Allinfo = [json objectForKey:#"Collection"];//I go into "Collection"
NSLog(#"All with response array: %#", Allinfo);
NSDictionary *datainfo = [Allinfo objectForKey:#"contact"];//i go into "contact"
after which i get
Data : (
{
attributeList = {
attribute = (
{
name = "display-name";
value = "tel:+";
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
},
{
attributeList = {
attribute = (
{
name = "display-name";
value = bob;
},
{
name = capabilities;
value = "TRANSFER";
},
{
name = relationship;
value = ACCEPTED;
}
);
resourceURL = "https://example.com";
};
contactId = "tel:+";
}
)
This starts from a { and i do not get a key for the next object so that i can get the values inside the JSOn
Is there any easier way to remove this or any other so that i can get values like name and value and store them in an array.
Thanks in advance
You have keys for all.
In fact you seem to get confused on array which is a part of attribute.
The outermost key is Data which contains array.
For each object of the array you have :
The first key is attributeList & contactD.
The value of attribute key is an array of 3 values. Each array contains key value pairs. keys are name & value.
I am not sure from where you got [Allinfo objectForKey:#"contact"]. Try to parse like below..
NSDictionary *Allinfo = [json objectForKey:#"Collection"];
NSArray *dataArray = [Allinfo objectForKey:#"Data"];
for(NSDictionary *dic in dataArray)
{
NSDictionary *attributeList=[dic objectForKey:#"attributeList"];
NSArray *attributeArray=[attributeList objectForKey:#"attribute"];
NSString *resourceURLString=[attributeList objectForKey:#"resourceURL"];
NSString *contactIdString=[dic objectForKey:#"contactId"];
for(NSDictionary *attributeDic in attributeArray)
{
NSString *nameString=[attributeDic objectForKey:#"name"];
NSString *valueString=[attributeDic objectForKey:#"value"];
}
}
You can use the following method for this
NSError *e = nil;
NSArray *itemArray = [NSJSONSerialization JSONObjectWithData:[response dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingMutableContainers error: &e];
if (!itemArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in itemArray) {
//Your Data
}
}

Resources