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
Related
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"]];
In my app, I am parsing the data using JSON
NSString * urlString=[NSString stringWithFormat:#"http://userRequest?userid=bala#gmail.com&latitude=59.34324&longitude=23.359257"];
NSURL * url=[NSURL URLWithString:urlString];
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:url];
NSError * error;
NSURLResponse * response;
NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString * outputData=[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"%#",outputData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:outputData error:nil];
NSLog(#"%#",jsonData);
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"success"] integerValue];
After this code executes, In my log it is printed as
({
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},
{
latitude = "80.000000000000000";
longitude = "30.000000000000000";
username = arun;
})
But while running, the app crashes, as
'NSInvalidArgumentException', reason: '-[__NSArrayM objectForKey:]: unrecognized selector sent to instance 0x910d8d0'
I think your problem is, that jsonParser objectWithString returns an array with dictionaries in it not dictionaries itself.
Try the following:
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
for(NSDictionary *dict in jsonData) {
NSLog(#"%#",dict);
}
Does that work for you ?
Your reponse is NSArray which contains NSDictionary. So frst get dictionary from array then access value. Also Your json not look like correct.
for (NSDictionary *dict in responseArray) {
double latitude = [dict[#"latitude"]doubleValue];
double longitude = [dict[#"latitude"] longitude];
NSString* name = dict[#"username"];
}
1. First of all you are getting NSArray in JSON
JSON Starts with "(" means NSArray
JSON Starts with "{" means NSDictionary
Here you are getting NSArray which has collection of NSDictionary,
{
latitude = "0.000000000000000";
longitude = "0.000000000000000";
username = sunil;
},...
2."success" key is not present in the JSON..
Fix
NSArray *jsonData = (NSArray *) [jsonParser objectWithString:outputData error:nil];
If([jsonData count]>0){
// Has some data
// Iterate NSDictionary and get data here
}
else{
// No Data
}
some where you are getting data from nsarray with using some object key. that key is invalid to fetching data from array
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.
I am using RestKit 0.9.4. I would like to post a JSON that has a key that needs to be populated from an object's attribute.
The JSON is as follows:
{
"types":[ {
"1" : "value1"
},
{
"7" : "value2"
} ]
}
I have an object with 2 NSString data members named keytype and value respectively .
keytype is the variable that has the values that appear for the key in the nested json above ( "1", "7" etc above ). mapKeyOfNestedDictionaryToAttribute will probably not work here because the dynamic attribute( to be used as key) is at the inner most level..
Can this be posted using RestKit?
Here's how you make that structure in an NSDictionary, and then post it as JSON using RestKit. Also, the response then maps to a model.
// make the inner dictionaries (probably would use a for loop for this
NSDictionary *dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"value1", #"1", nil];
NSDictionary *dict7 = [[NSDictionary alloc] initWithObjectsAndKeys:#"value2", #"7", nil];
// put them in an array
NSArray *types = [[NSArray alloc] initWithObjects:dict1, dict7, nil];
// now put the array in a dictionary
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:types, #"types", nil];
// create a JSON string from your NSDictionary
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString = [[NSString alloc] init];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
// make the post using the objectManager if you want to map the response to a model
RKObjectManager* objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:#"/api/" delegate:self block:^(RKObjectLoader* loader) {
loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON
loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Plan class]];
loader.resourcePath = #"/api/";
loader.method = RKRequestMethodPOST;
loader.params = [RKRequestSerialization serializationWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON];
}];
{"response":[33689822,64091979,69682048,74160161]}
-
- (void)requestCompleted:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
NSLog(#"okRequest|| %#",responseString);
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithString:responseString];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
//all other func..
NSLog(#"%# ", status);///This func prints only "response"
}
}
How I can get array of numbers in "response"? (33689822,64091979,69682048,74160161)
Try this:
for (NSNumber *number in [statuses objectForKey:#"response"]) {
NSLog(#"%#", number);
}
You can either parse the JSON data yourself, or better, use a library like TouchJSON to do it for you.
Try using JSONFragmentValue directly.
NSString *response=[request responseString];
id usableResp = [response JSONFragmentValue];