Json conversion problems: invalid characters found - ios

I am converting my array to json object, then sending it to server. But It is showing some invalid characters when i get them in server end. like '\n', & '\'.
Here is a sample of my data which i get at the server end:
('[\n "{\\"id\\":2,\\"qrCode\\":\\"KdcUfeddHpbepeXnyiKFjcfedHp\\",\\"activity\\":\\"2\\",\\"time\\":\\"64485\\",\\"image_base64\\":\\"\\/9j\\/4AAQSkZJRgABAQAA"}"\n]');
But it should look like the following:
('[{"id":2,"qrCode":"KdcUfeddHpbepeXnyiKFjcfedHp","activity":2,"time":1372757846,"image_base64":"AA\\u003d\\u003d\\n"}]');
here is the code:
-(void)setOflynData2JsonFormat{
if (!([self.getOfflineData count] == 0)) {
NSArray *array = [self getOfflineData];
for (int i = 0; i<[array count]; i++) {
uniqueId++;
NSNumber *uId = [NSNumber numberWithInt:uniqueId];
OfflineTableObject *offObj = [array objectAtIndex:i];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:uId forKey:#"id"];
[dict setValue:offObj.qrCode forKey:#"qrCode"];
[dict setValue:offObj.offlineStatus forKey:#"activity"];
[dict setValue:offObj.time forKey:#"time"];
[dict setValue:offObj.imageData forKey:#"image_base64"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
NSLog(#"Json string : %#",singleJsonString);
arrayOfJsonString = [[NSMutableArray alloc]init];
[arrayOfJsonString addObject:singleJsonString];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonDataFromArray encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
int check = [obj sendOfflynData2Server:jsonString];
}
}
So, where is the problem? Thnaks in advance for the help.

The problem is that you are translating your data to JSON twice.
You first translate all your dicts to json with
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
add them to an array, and then re-translate the array to JSON with
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
So instead of producing the expected JSON output, it serialize an array of JSON strings, hence the escaping mess.
Instead, you should just add your dicts to the array, and then serialize the whole thing :
arrayOfJsonString = [[NSMutableArray alloc]init];
for (int i = 0; i<[array count]; i++) {
// snip
[arrayOfJsonString addObject:dict];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];

Related

How to send multiple parameters in ios?

How to send parameters in json format?
Below are my input parameters :
[
{
"LoginID":151,
"UserID":0,
"SubUserID":0,
"WorkGroupID":92,
"WorksFor":"Doctor",
"UserWorkGroup":0
},
{
"SortingName":"",
"Searching":true,
"SortingOrder":"Desc",
"RecordsCount":10,
"PageIndex":0
}
]
Previously I was sending parameters as below :
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:#"55",#"LoginID",#"0",#"UserID",#"0",#"SubUserID",#"90",#"WorkGroupID",#"Doctor",#"WorksFor",#"0",#"UserWorkGroup",nil] andRequestType:#"POST"];
how to sent like this but now i need to add some more input mentioned above ?
Just use following code..
NSMutableArray * myArray = [[NSMutableArray alloc]init];
NSMutableDictionary * myData = [[NSMutableDictionary alloc]init];
[myData setValue:#"151" forKey:#"LoginID"];
[myData setValue:#"0" forKey:#"UserID"];
[myData setValue:#"0" forKey:#"SubUserID"];
[myData setValue:#"92" forKey:#"WorkGroupID"];
[myData setValue:#"Doctor" forKey:#"WorksFor"];
[myData setValue:#"0" forKey:#"UserWorkGroup"];
[myArray addObject:myData];
myData = [[NSMutableDictionary alloc]init];
[myData setValue:#"," forKey:#"SortingName"];
[myData setValue:#"1" forKey:#"Searching"];
[myData setValue:#"Desc" forKey:#"SortingOrder"];
[myData setValue:#"10" forKey:#"RecordsCount"];
[myData setValue:#"0" forKey:#"PageIndex"];
[myArray addObject:myData];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"Your final jsonData as string:\n%#", jsonString);
If you want to send this data to Server, then you can use this code:
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:myArray options:0 error:nil];
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:dataToSend] andRequestType:#"POST"];
You can do something like this,
NSDictionary *dict1 = #{#"LoginID":#"151",#"UserID":#"0",#"SubUserID":#"0",#"WorkGroupID":#"92",#"WorksFor":#"Doctor",#"UserWorkGroup":#"0"};
NSDictionary *dict2 = #{#"SortingName":#",",#"Searching":#"true",#"SortingOrder":#"Desc",#"RecordsCount":#"10",#"PageIndex":#"0"};
NSArray *arr = [NSArray arrayWithObjects:dict1,dict2, nil];
NSData *dataToSend = [NSJSONSerialization dataWithJSONObject:arr options:0 error:nil];
[getProfileServices sendSynchronousPostRequestWithStringForAction:getProfileURL andParameters:[[NSDictionary alloc] initWithObjectsAndKeys:dataToSend andRequestType:#"POST"];
Hope this will help :)
add it in NSMutableArray and add that array to NSDictionary. like;
{"LoginID":151,"UserID":0,"SubUserID":0,"WorkGroupID":92,"WorksFor":"Doctor","UserWorkGroup":0}
this goes in NSMutableArray and NSMutableArray goes to NSDictionary
Simple way to put array into the dictionary is
#{#[element],#[element],#[element]}

How to parse such a json array?

Im having hard time while trying to parse the following json array. How to parse it. The other answers in web doesn't seem to solve my problem.
{
"status": 1,
"value": {
"details": [
{
"shipment_ref_no": "32",
"point_of_contact": {
"empid": ""
},
"products": {
"0": " Pizza"
},"status": "2"
},
{
"shipment_ref_no": "VAPL/EXP/46/14-15",
"point_of_contact": {
"empid": "60162000009888"
},
"products": {
"0": "MAIZE/CORN STARCH"
},
"status": "5"
}
]
}
}
I have to access the values of each of those keys.
Following is my code
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
This is how you can parse your whole dictionary:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *details = [[dataDictionary objectForKey:#"value"] objectForKey:#"details"];
for (NSDictionary *dic in details) {
NSString *shipmentRefNo = dic[#"shipment_ref_no"];
NSDictionary *pointOfContact = dic[#"point_of_contact"];
NSString *empId = pointOfContact[#"empid"];
NSDictionary *products = dic[#"products"];
NSString *zero = products[#"0"];
NSString *status = dic[#"status"];
}
NSString *pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
//argsArray holds objects in form of NSDictionary.
for(NSDictionary *response in argsArray) {
//String object
NSLog(#"%#", [response valueForKey:#"shipment_ref_no"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"point_of_contact"] valueForKey:#"empid"]);
//String object
NSLog(#"%#", [response valueForKey:#"status"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"products"] valueForKey:#"0"]);
}
I believe you should surely ask your server developer to update the response format.
Also, you can always use Model classes to parse your data. Please check this, How to convert NSDictionary to custom object.
And yes, I'm using this site to check my json response.
EDIT: Following answer is in javascript!
You can parse your json data with:
var array = JSON.parse(data);
and then you can get everything like this:
var refno = array["value"]["details"][0]["shipment_ref_no"];
you can parse like ...
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *dictValue = [[NSDictionary alloc] initWithDictionary:[jsonDic objectForKey:#"value"]];
NSArray *arrDetails = [[NSArray alloc] initWithArray:[dictValue objectForKey:#"details"]];
for (int i=0; i<arrDetails.count; i++)
{
NSDictionary *dictDetails=[arrDetails objectAtIndex:i];
NSDictionary *dictContact = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"point_of_contact"]];
NSDictionary *dictProduct = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"products"]];
}
NSDictionary *response = //Your json
NSArray *details = response[#"value"][#"details"]
etc. Pretty easy
Update your code as follows. You are trying to read the details array from the top level whereas in your data its inside the value key. So you should read the value dict and within that read the details array.
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *valueDict = [jsonDic objectForKey:#"value"];
NSArray *argsArray = [[NSArray alloc] initWithArray:[valueDict objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
I think your problem is that you have:
NSLog(#"keys = %#", jsonDic[#"values"]);
But it should be:
NSLog(#"keys = %#", jsonDic[#"value"]);
Below is code for parsing JSON array. i have used to parse JSON array from file but you can also do this using response link also.I have provided code for both and are below.
// using file
NSString *str = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:str];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
// using url
NSURL *url = [NSURL URLWithString:#"www.xyz.com"]; // your url
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);

JSON Parsing: NSArray POST

How to POST NSArray values in JSON or Is there any possible to POST JSON values.
I thing this is useful, otherwise I modify something in code
NSMutableArray * arr = [[NSMutableArray alloc] init];
// assume that this is your Array
[arr addObject:#"1"];
[arr addObject:#"2"];
// convert the NSArray to NSdata , the reason is always the web service get string only
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
// finally append the -- jsonString to your web service

How to fetch NSString from a JSON array of dictionaries?

This is my JSON:
-elements: [
{
HomeworkElementSession: {
id: "608743",
name: "Interval for x",
description: "",
}
}
]
...
I was able to get to the point where I have an actual NSArray representing the "elements" node and therefore containing only one object in the array.
But I have no idea how to reach this string "name".
What i did was:
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
But i get nil in Log.
What am I doing wrong ?
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* homeworkSession = [elements objectAtIndex:i];
NSDictionary* dataDict = [homeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
You need to get the Dictionary for key HomeworkElementSession first
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(int i=0; i<elements.count; i++){
NSDictionary* mainhomeworkSession = [elements objectAtIndex:i];
NSDictionary* homeworkSession = [mainhomeworkSession objectForKey:#"HomeworkElementSession"];
NSString* name = [homeworkSession objectForKey:#"name"];
NSLog(#"%#",name);
}
Hope it helps you..!
NSMutableArray *elements = [singleHomework objectForKey:#"elements"];
for(NSDictionary *dict in elements){
NSDictionary* dataDict = [dict objectForKey:#"HomeworkElementSession"];
NSString* name = [dataDict objectForKey:#"name"];
NSLog(#"%#",name);
}
Try this may be help full ,
Note: you are getting output in NSString so use this
NSString *singleHomework = #"your data";
NSMutableDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:[singleHomework dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:Nil];
NSMutableArray *dataArray = [dataDic valueForKey:#"elements"];
NSLog(#"Name Print %#",[dataArray[0] valueForKey:#"name"]);
First, I'm not sure why you have a hyphen in the dictionary key "-elements". That could be a problem. However, your main problem is that your JSON is an array containing a single dictionary which then contains a dictionary (HomeworkElementSession) which has attributes.
NSString * json = #"{\"elements\": [{\"HomeworkElementSession\": {\"id\": \"608743\", \"name\":\"Interval for x\", \"description\": \"\"}}]}";
NSData * jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&e];
NSLog(#"dict=%#", dict);

Parsing a JSON array with dictionaries

I'm having some trouble getting to the data I want to in the JSON file. Here is a shortened version of the output from my console:
{
AUD = {
15m = "125.15547";
24h = "124.74";
buy = "121.0177";
last = "125.15547";
sell = "123.44883";
symbol = "$";
};
BRL = {
15m = "120.34";
24h = "120.34";
buy = "120.34";
last = "120.34";
sell = "120.34";
symbol = "R$";
};
CAD = {
15m = "129.08612";
24h = "131.07";
buy = "128.66227";
last = "129.08612";
sell = "129.08612";
symbol = "$";
};
}
I'm trying to parse the file using the built in JSON parsing library. Here is the parser in my viewDidLoad method:
_tickerArray = [NSMutableArray array];
NSURL *tickerDataURL = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
NSArray *ar = [NSArray arrayWithObject:dataDictionary];
for (NSString *key in [dataDictionary allKeys]) {
for (NSDictionary *dict in ar) {
TickerData *t;
t.currency = [dict objectForKey:key];
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
I want to store the currency code (like AUD or BRL) into t.currency along with some of the other data contained in the currency dictionary but now my app is crashing.
Error code:
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
None of the objects seem to get added to the _tickerArray
Help?
EDIT: Getting the keys to display with the proper data populating other fields:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];
TickerData *t=[[TickerData alloc] init];
t.currency = key;//EDITED
t.symbol = [dic objectForKey:#"symbol"];
t.last = [dic objectForKey:#"last"];
[_tickerArray addObject:t];
}
t is nil, you have to alloc/ init it:
TickerData *t = [[TickerData alloc] init];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
//NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED
for (NSString *dickey in [dic allKeys]) { //MODIFIED
NSDictionary *dict=[dic objectForKey:dicKey];//ADDED
TickerData *t=[[TickerData alloc] init];//ALLOC INIT ?
t.currency = key;//EDITED
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
Your data doesn't contain any array, its all dictionaries, try the above code see comments too..
Hope it works..
Edited:
Yes you have initialize the object too, as suggested above in other answers..
Try it....
NSURL *url = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSLog(#"API : %#",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:#"AUD"];
NSLog(#"%#",dict);
NSString *last = [dict valueForKey:#"last"];
NSLog(#"%#",last);

Resources