Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to format a JSON string of below format using NSJSONSerialization:
{
"data":{"userName":"rrullo","password":"rrullo!"},
"meta":{"appId":"S3B9CU4R2B9JTXV9254Y","appVersion":"2.1.0","serverVersion":"1.1.0","platform":"iOS","deviceToken":"1234","tm_session_id":"BB0000001234"}
}
But I have no clue how to achieve this format though. Can someone help me please ......
First fill two NSDictionaries with your 'meta' and 'data' info. Then add those into a main NSDictionary and then serialize using NSJsonSerialization
NSDictionary * metaDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"appId", #"S3B9CU4R2B9JTXV9254Y", #"appVersion", #"2.1.0", #"serverVersion", #"1.1.0", #"platform", #"iOS",..., nil];
NSDictionary * dataDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"userName", #"rrullo", #"password", #"rrullo!", nil];
NSDictionary * mainDict = [[NSDictionary alloc] initWithObjectsAndKeys:
#"data", dataDict, #"meta", metaDict, nil];
Now you can use NSJsonSerialization to convert that mainDict to a NSString
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mainDict
options:NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
Hope this helps
NSDictionary dictData = #{ #"UserName":#"rrullo", #"password":#"rrullo!"};
NSDictionary dictMeta = #{ #"appId":#"S3B9CU4R2B9JTXV9254Y", etc};
NSDictionary dictJSON = #{ #"data":dictData, #"meta":dictMeta };
NSError *error = nil;
NSData *dataJSON = [NSJSONSerialization dataWithJSONObject:dictJSON
options:NSJSONWritingPrettyPrinted
error:&error];
if (!error) {
NSString *jsonString = [[NSString alloc] initWithData:dataJSON encoding:NSUTF8StringEncoding];
} else {
NSLog(#"Error: %#", error);
}
Related
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);
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"];
This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
I have some values in an array ,using dictionary I need to show these values through some key value
{
"table_id": "180PTTBL",
"table_name": "180 Points",
"stake": 100,
"game_type": "180PT"
}
Please help me out this problem
You can use NSJSONSerialization
NSError *e = nil;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!dict) {
NSLog(#"Error parsing JSON: %#", e);
} else {
.. do your stuff
}
NSString *jsonString = #"YOUR_JSON_STRING";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[json objectForKey:#"table_id"]);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am very new to iOS application development and I am getting the below response from the server:
"[{\"EmployeeID\":\"000001\",\"EmplyeeName\":\"ABCD EFGHI\"},
{\"EmployeeID\":\"000002\",\"EmplyeeName\":\"ADGHT ASASASAS\"}]"
Please anybody help me out on how to use employee ID and employee name in my application.
Your JSON data looks like "nested JSON", which means that you have to deserialize it twice.
The first deserialization extracts a string from your JSON data:
NSData *response = ...; // your data
NSError *error;
NSString *innerJson = [NSJSONSerialization JSONObjectWithData:response
options:NSJSONReadingAllowFragments error:&error];
Now innerJson is the string
[{"EmployeeID":"000001","EmplyeeName":"ABCD EFGHI"},{"EmployeeID":"000002","EmplyeeName":"ADGHT ASASASAS"}]
which is again JSON data. The second deserialization extracts the array:
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
And now you can access it like
for (NSDictionary *entry in entries) {
NSString* employeeID = [entry objectForKey:#"EmployeeID"];
NSLog(#"%#", employeeID);
}
NSData *response = ...;
NSArray *entries = [NSJSONSerialization JSONObjectWithData:response
options:0
error:nil];
for(NSDictionary* entry in entries) {
NSString* employeeID = [entry objectForKey:#"EmployeeID"];
}
Look JSON Parser your response is JSON so you need to get that data from json.
NSURL * url=[NSURL URLWithString:#"<YourURL>"];
NSData * data=[NSData dataWithContentsOfURL:url];
NSError * error;
NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSMutableArray * EmployeeID=[[NSMutableArray alloc]init];
NSMutableArray * EmployeeName=[[NSMutableArray alloc]init];
NSArray * responseArr = json[#"geonames"];
for(NSDictionary * dict in responseArr)
{
[EmployeeID addObject:[dict valueForKey:#"EmployeeID"]];
[EmployeeName addObject:[dict valueForKey:#"EmplyeeName"]];
}
now you get the EmployeeID,EmployeeName array now you can used anywhere where you want.
Take a look at:
NSJSONSerialization
Use this:
NSData* yourData = [[NSData alloc] initWithContentsOfURL: yourURL];
NSarray* yourJSON = [NSJSONSerialization JSONObjectWithData:yourData options:kNilOptions error:nil];
Hope this help you :)
Try to use this:
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
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.