SBJson Parse Data on iOS - ios

I want to parse those Json that has a structure like this on iOS, with SBJSon libs
Can anyone help me? thanks so much!
{"error":{"username":["The username has already been taken."],"email":["The email has already been taken."]}}

NSString *str=#"{\"error\":{\"username\":[\"The username has already been taken.\"],\"email\":[\"The email has already been taken.\"]}}";
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];
NSLog(#"dic is %#",json);
//output
dic is {
error = {
email = (
"The email has already been taken."
);
username = (
"The username has already been taken."
);
};
}
Using SBJSon
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [str JSONValue];

SBJsonParser * parser = [[SBJsonParser alloc] init];
NSObject * responseobj = [parser objectWithData:data]; // for NSData
NSObject * responseobj = [parser objectWithString:string]; // for NSString
In your case "responseobj" will be of type NSDictionary.

Related

NSDictionary structure not getting done properly

i want to make a structure like following using NSDictionary
{
"request":
{
"email":"manger#abc.com",
"password":"manager"
}
}
I'm using the following code in objective C
NSDictionary *paramsDic = [[NSDictionary alloc] initWithObjectsAndKeys:
#"manger#hall.com",#"email",
#"manager",#"password",
nil];
NSDictionary *req = [[NSDictionary alloc] initWithObjectsAndKeys:
paramsDic,#"request",
nil];
but it returns the following response
{
request =
{
email = "manger#abc.com";
password = manager;
};
}
it shows semicolons instead of commas , one extra semicolon and keys are not in inverted commas
Convert req to JSON object
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"%#", jsonData);

Deserialise JSON String in Objective C

I received NSData object data from REST API. That contains JSON data which I want to parse.
{
JsonResult = "[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
}
This statement gave me the result as a String like below which I am not able to parse as JSON.
myData = [data valueForKey:#"JsonResult"];
"[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
When I try to pass this mydata to JSONSerialization the code crashes.
How do I cast the above string to NSDictionary so that I can parse them and use the values of IsAuth and User.?
Code:
[LDService authenticateUser:Uname.text passwordString:Password.text completeBlock:^(NSData * data){
NSError *error;
NSData *jsonData;
NSString *jsonString = nil;
NSMutableDictionary *jsonDict;
if([NSJSONSerialization isValidJSONObject:data])
{
jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
NSLog(#"Formatted string %#",formattedString);
[jsonDict setObject:formattedString forKey:#"JsonResult"];
NSLog(#"Parsed json %#",jsonDict);
}];
Pass your data as data
NSError *error;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:data])
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
then replace occurance of #"\\\" with #"'"
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
then use this formattedString.
I have investigates your json file from Json formatter & Validator, there are lots of error in your json file, so first check your file from this validator and this formatter gives you error with description. Re-build your json file, if you still getting any problem then ask.

Convert JSON array to Objective-C in iOS

I am new to iOS development. I am trying to covert JSOn array values to Objective-C values. My JSON values are like this:
{"result":
[{"alternative":
[{"transcript":"4"},
{"transcript":"four"},
{"transcript":"so"},
{"transcript":"who"}],
"final":true}],
"result_index":0}
I have tried it this way:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
speechArray is always null. How to resolvee this problem?
At the same time I would like to print transcript values.
I think the problem might be in initializing the array and Dictionary.
Try doing this,
NSDictionary *speechResult = [NSDictionary new];
NSArray *speechArray = [NSArray new];
Hope it helps..
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];//data is your response from server as NSData
if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
NSArray * speechArray = json[#"result"];
}
NSLog(#"speech array %#",speechArray);
Did you check the value in NSDictionary (speechResult).
If it is nil, check the json data isValid or not.
NSError *error;
if ([NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error] == nil)
{
// Check the error here
}else {
// here check whether it is a dictionary and it has key like #Bhadresh Mulsaniya mentioned.
}
If returns nil, then you check the error to understand what's wrong.
try this may be it will help you:-
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult = [NSDictionary new];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];
NSLog(#"%#",speechArray);
NSLog(#"Response is of type: %#", [speechArray class]);
try this code,
restaurantdictionary = [NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:&e];
NSMutableArray *main_array=[[NSMutableArray alloc]init];
main_array=[restaurantdictionary valueForKey:#"results"];
NSLog(#"main_array %#", main_array);
its working for me, hope its helpful
You have to initialize the array before using it,
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:speechrequestString]];
NSError *error;
NSDictionary *speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray= [[NSArray alloc] init];
speechArray= [speechResult valueForKey:#"result"];
if (speechArray.count>0) {
NSDictionary * alternativeDictn = [speechArray objectAtIndex:0];
NSArray *alternativeAry= [[NSArray alloc] init];
alternativeAry = [alternativeDictn objectForKey:#"alternative"];
NSLog(#"%#",alternativeAry);
}
NSLog(#"Response is of type: %#", [speechArray class]);
Using this code you will get following result,
(
{
transcript = 4;
},
{
transcript = four;
},
{
transcript = so;
},
{
transcript = who;
}
)
Try out the below code to get the transcripts:
NSData* jsonData = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *responseObj = [NSJSONSerialization
JSONObjectWithData:jsonData
options:0
error:&error];
if(! error) {
NSArray *responseArray = [responseObj objectForKey:#"result"];
for (NSDictionary *alternative in responseArray) {
NSArray *altArray = [alternative objectForKey:#"alternative"];
for (NSDictionary *transcript in altArray) {
NSLog(#"transcript : %#",[transcript objectForKey:#"transcript"]);
}
}
} else {
NSLog(#"Error in parsing JSON");
}
You should alloc your dictionary first like this-
NSDictionary *speechResult = [[NSDictionary alloc]init];
speechResult= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *speechArray = [[NSArray alloc]init];
speechArray= [speechResult valueForKey:#"result"];

I need json string without double quotes in keys in ios

I upload the json string to the server like
NSDictionary *values = [[NSDictionary alloc]initWithObjectsAndKeys:#"name", #"objective", nil];
NSArray *array = [[NSArray alloc]initWithObjects:values,nil];
NSDictionary *result = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"objectives", nil];
I use the following code to convert the dictionary to JSON:
id obj = result;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I get correct json like
{ "objectives":[
{"objective":"name"}
]
}
This is correct json but I need json string like
{ objectives:[
{"objective":"name"}]
}
Is it possible to create without double quotes in key in iOS?
Only this json string we get the response otherwise I get error.
if it is only the first key that you want to remove quotes from, you can use the following quick workaround
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\"objectives\"" withString:#"objectives"]];

SBJSON issues with key value NSDictionary

I have got JSON string as below:
{"status": "ok", "secret": "d2d388eb3a24aaacb365597f69a2bf97", "client": "100006", "expires": "1345721042"}
For parse JSON object I'm using SBJSON library.
This is my code that I have used for retrieve data from JSON object:
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObjects = [jsonParser objectWithString:[request responseString] error:&error];
but when I try to out into NSLog my dictionary I have not a pair key value object, but have just key for example: status, secret, client and expires.
How can I get NSDictionary with key value object using SBJSON library
{
status = "ok";
secret = "d2d388eb3a24aaacb365597f69a2bf97";
}
It's because you are setting the result of your parse to a NSArray object. You should store the results of the JSONParser as a NSDictionary object to store it as key value pairs
NSDictionary *jsonObjects = [jsonParser objectWithString:[request responseString] error:&error];
Then you can access them like so:
NSString *status = [jsonObjects objectForKey:#"status"];
NSString *secret = [jsonObjects objectForKey:#"secret"];
// and so on

Resources