i am try to convert this json data into dictionary but I can't please help me.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I know only to convert from Dictionary to JSON like this
NSMutableDictionary * location = [[NSMutableDictionary alloc]init];
[location setValue:mobileCountryCode forKey:#"mobileCountryCode"];
[location setValue:mobileNetworkCode forKey:#"mobileNetworkCode"];
[location setValue:cellId forKey:#"cellId"];
[location setValue:locationAreaCode forKey:#"locationAreaCode"];
NSData *data = [NSJSONSerialization dataWithJSONObject:requestbodyInputDict options:NSUTF8StringEncoding error:nil];
NSString* jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"jsonString.....%#",jsonString);
NSData *requestBody = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
so please help me how to revers this process how to handle this.
Just check this code. It will convert your json to NSdictionary
NSString *jsonString = #"{ \"homeMobileCountryCode\": 310, \"homeMobileNetworkCode\": 260, \"radioType\": \"gsm\", \"carrier\": \"T-Mobile\", \"cellTowers\": [ { \"cellId\": 39627456, \"locationAreaCode\": 40495, \"mobileCountryCode\": 310, \"mobileNetworkCode\": 260, \"age\": 0, \"signalStrength\": -95 } ], \"wifiAccessPoints\": [ { \"macAddress\": \"01:23:45:67:89:AB\", \"signalStrength\": 8, \"age\": 0, \"signalToNoiseRatio\": -65, \"channel\": 8 } ] }";
NSError *jsonError;
NSData *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
Use String replace method to replace " with \" it will work
what you are doing is you are directly accessing the "mobileCountryCode", "mobileNetworkCode" and so on.. which are element of json array "cellTowers" so if you want those values you can first have an array of "cellTowers" and there you go...
Related
I want to send below JSON parameter in an API call, but the string of contacts array which is used below is confusing and I'm unable to form it in iOS. Below is the working JSON parameter tested in Rest client. How to form a similar pattern of string containing an array of contacts in iOS?
Working JSON Parameter,
{
"contacts": "[\"5555228243\",\"919677012480\"]",
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
My code below for conversion,
NSMutableDictionary *reqData = [[NSMutableDictionary alloc]init];
[reqData setObject:[FMCoredDataUtility fetchDetailForKey:kmobileNumber] forKey:#"phno"];
[reqData setObject:[FMCoredDataUtility fetchUserNameForKey:kuserName ]forKey:#"name"];
[reqData setObject:#"iphone" forKey:#"device"];
[reqData setObject:#"key" forKey:#"key"];
[reqData setObject:[self getMobileContacts ] forKey:#"contacts"];
[reqData setObject:#"files" forKey:#"files"];
-(NSArray*)getMobileContacts{
contactNumbers = [addUtility getContactNumbers];
for ( int i = 0; i < [contactNumbers count]; i++) {
[filteredContacts addObject:[[[contactNumbers objectAtIndex:i] componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:#""]];
}
return filteredContacts;
}
Framed error JSON parameter,
{
"contacts": [
"5555228243",
"5554787672",
"4085555270",
"4085553514",
"5556106679",
"5557664823",
"7075551854",
"8885555512",
"8885551212",
"5555648583",
"4155553695",
"919677012480"
],
"phno": "919791871448",
"device": "iphone",
"key": "key",
"name": "Logunath Subramaniyan",
"files": "files"
}
and error I'm getting in console is,
value __NSCFConstantString *
#"JSON text did not start with array or object and option to allow fragments not set."
0x000000010cf2ed50
Here is a way in which you can convert your ios array to JSON string
NSArray *contactsArray = [self getMobileContacts ];//This will be your contacts array
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
[reqData setObject:jsonString forKey:#"contacts"];
I am trying to parse the following json into my iOS code.
{
"test": [
{
"id": "21",
"lat": "53.343377977116916",
"long": "-6.2587738037109375",
"address": "R138, Dublin, Ireland",
"name": "td56",
"distance": "0.5246239738790947"
},
{
"id": "11",
"lat": "53.343377977116916",
"long": "-6.245641708374023",
"address": "68-130 Pearse Street, Dublin, Ireland",
"name": "test1",
"distance": "0.632357483022306"
}
]
}
I am able to view the full json in my logs with the following code:
NSURL *blogURL = [NSURL URLWithString:#"URLHERE"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *test = [dataDictionary objectForKey:#"test"];
NSLog(#"%#",dataDictionary);
if I change data dictionary to test in the log, I can display after the test root in my json , but if I try setup arrays to view, let's say the ID, the entire app will crash.
Could someone direct me in the right way to, let's say, display all the names in the NSLog? Each method I've tried has resulted in the application crashing.
Test is an array:
NSArray *test = [dataDictionary objectForKey:#"test"];
NSLog(#"test =%#", test);
for(NSDictionary *coordinates in test){
NSLog(#"id = %#", coordinates[#"id"]);
NSLog(#"lat = %#", coordinates[#"lat"]);
NSLog(#"long = %#", coordinates[#"long"]);
}
NSArray *array = [dataDictionary valueForKey:#"test"];
for(int i = 0; i < array.count; i++){
NSLog(#"%#", [array[i] valueForKey:#"name"]);
}
like that u can get NSLog whatever key you want
for id
NSLog(#"%#", [array[i] valueForKey:#"id"]);
for lat
NSLog(#"%#", [array[i] valueForKey:#"lat"]);
and so on.....
Happy coding
i am getting the response from the server in JSON array form like below :
{
"status": "success",
"data": [
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "10632",
"loginEmail": "Raushan#gmail.com",
"auth_authorizationCode": "4cb8c5e8a7f5",
"accountType": "flickr",
"auth_Token": "23104658-d2e65d5f94554652",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
},
{
"auth_Secret_ticket_refresh": "NULL",
"userId": "19629",
"loginEmail": "Ipad#gmail.com",
"auth_authorizationCode": "8b909cb3e0e1",
"accountType": "flickr",
"auth_Token": "77645323118718-bac668bc2b95ad89",
"userName": "betterlabpune",
"auth_subdomain": "NULL"
}
]
}
I want to extract the value from JSON array for the 0 index, value for "userId" and "userName".
i had tried to extract values in many ways ,below is my code:
NSMutableData * _responseData = [[NSMutableData alloc]init];
[_responseData appendData:data];
NSJSONSerialization *dataAsString=(NSJSONSerialization*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
// dataJson=(NSDictionary*)[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"data in register reponse : %#",dataAsString);
NSJSONSerialization *json;
NSDictionary *dataJson;
NSError *error;
NSDictionary *JSONE = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
NSLog(#"JSONE : %#",JSONE);
json=[NSJSONSerialization JSONObjectWithData:_responseData
options:NSJSONReadingMutableLeaves
error:&error];
[self processData:dataJson];
dataJson=[[NSDictionary alloc]init];
dataJson=(NSDictionary *)json;
NSString * status=[dataJson objectForKey:#"status"];
NSString * message=[[dataJson objectForKey:#"data"]objectForKey:#"id"];
NSLog(#"status : %#",status);
NSLog(#"message: %#",message);
NSMutableArray *argsArray = [[NSMutableArray alloc] init];
argsArray= [dataJson valueForKeyPath:#"status"];
NSLog(#" client Id : %#", [argsArray objectAtIndex:0]);
bet every time i get null in my result.
Please help me out.
Thank you for your precious time.
try this...
if ([[dataJson valueForKey:#"status"]isEqualToString:#"success"])
{
NSMutableArray *tempArray=[NSMutableArray array];
for (NSDictionary *tempDic in [dataJson valueForKey:#"data"])
{
[tempArray addObject:[tempDic valueForKey:#"userId"]];
}
NSLog(#"%#",tempArray);
}
I have the following JSON from a Web service:
[
"{
"count":2,
"offers":{
"0":{
"nodeID":"654321",
"publicationDate":"1396272408",
"title":"My first title",
"locations":"New York City"
},
"1":{
"nodeID":"123456",
"publicationDate":"1396272474",
"title":"My second title",
"locations":"San Diego"
}
},
"error":"null",
"result":"success"
}"
]
I need to map this JSON to a NSDictionary. How can I do that?
I already tried the following
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
but it only gives me a dictionary with one object in it. I need to access all the fields of the JSON such as "count", "offers" etc. How can I achieve this?
You JSON output is not a dictionary but an array.
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSarray *parsedObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&localError];
for(NSDictionary *dict in parsedObject) {
NSNumber *count = [dict objectForKey:#"count"];
}
But the offer node is just weird, this would be better as an array.
Get your data in this form ... Your json Give error of ".....
[
{
"count": 2,
"offers":
{
"0": {
"nodeID": "654321",
"publicationDate": "1396272408",
"title": "Myfirsttitle",
"locations": "NewYorkCity"
},
"1": {
"nodeID": "123456",
"publicationDate": "1396272474",
"title": "Mysecondtitle",
"locations": "SanDiego"
}
},
"error": "null",
"result": "success"
}
]
You get data In Array [ having Dictionary in dictionary ....
Developing for the iPad, I have created a file that i call Coordinates.geojson. I would like to access it from within a classfile called JsonDecoder.m
Here is JsonDecoder.m
#implementation JsonDecoder
- (id)initWithJson
{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Coordinates" ofType:#"geojson"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSError *error;
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
return self;
}
- (NSArray*) getCoordinatesFromShelf:(NSString *) bookShelfName
{
NSArray *coordinates = [[[_json objectForKey:#"shelf1"] objectForKey:#"coordinates"]objectAtIndex:1];
for(id i in coordinates)
NSLog(#"%#",i);
return coordinates;
}
#end
And my Coordinates.geojson:
{
"shelf1": {
"name": "six.png",
"coordinates": [
[
14,
25,
329,
138
],
[
14,
185,
329,
138
],
[
14,
344,
158,
138
],
[
185,
344,
158,
138
],
[
14,
94,
158,
138
],
[
185,
500,
158,
138
]
]
}
}
How can i retreive these values from within a class file?
Thanks!
In iOS >= 5 you can parse it without external libraries
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Coordinates" ofType:#"geojson"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
But the content of the file isn't a valid JSON string.
If possible change it to something like:
{
"shelf1": {
"name": "six.png",
"coordinates": [
[
14,
25,
329,
138
],
[
14,
185,
329,
138
],
[
14,
344,
158,
138
],
[
185,
344,
158,
138
],
[
14,
94,
158,
138
],
[
185,
500,
158,
138
]
]
}
}
Then you can access it with:
NSDictionary *shelf1 = [json objectForKey:#"shelf1"];
//OR
NSArray *coordinates = [[json objectForKey:#"shelf1"] objectForKey:#"coordinates"];
Solved it.
The above worked perfectly
I had forgot to set target membership to my project for the geojson file.
To do this, mark your jsonfile, click on the fileinspector and toogle the checkbox of your project at "Target Membership"
Thanks.