I have a problem parsing JSON string in Objective C:
My JSON:
{"messages":[{"nick":"Tim","message":"Hallo","time":"06.07.2012 13:26:41"}]}
My Objective C Code:
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:#"..URL.."];
NSArray *messages = [data objectForKey:#"messages"];
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:messages
options:NSJSONReadingMutableLeaves
error:&error];
NSString *nick = [json objectForKey:#"nick"];
NSString *message = [json objectForKey:#"message"];
But this doesn´t work and I don´t know what to do!
Your JSON is a dictionary of arrays of dictionaries, i.e. {[{}]}
NSArray *messages = [json objectForKey:#"messages"];
NSString* nick = [[messages objectAtIndex:0]objectForKey:#"nick"]
Related
#"SaveRegistrationIDResult" : #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"
I'm finding it impossible to fetch data from this json string.
I'm getting the table Table Object as a NSDictionary using this code.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSData *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
but I getting errors for everything i try ahead.
I'd like to fetch data from within the Table array ('Return_Code') and print it in a Log.
You are getting json string so you can parse it like,
id jsonString = #"{\"Table\":[{\"Return_Code\":1,\"Return_Message\":\"ALREADY REGISTERED\"}]}"; // or [yourDictionary objectForKey : #"SaveRegistrationIDResult"];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Now you can get value of any key from above object like,
NSArray *arr = [jsonObject objectForKey : #"Table"];
NSLog(#"your result : %#", arr);
Lion's comment worked.
This is how I fetched the value. Any optimizations welcome.
NSMutableDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *processedJsondata = [jsonData objectForKey:#"SaveRegistrationIDResult"];
NSData *tableData = [processedJsondata dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *tableJsonObject = [NSJSONSerialization JSONObjectWithData:tableData options:0 error:nil];
NSArray *tableArray = [tableJsonObject objectForKey:#"Table"];
NSDictionary *tableObject = [tableArray objectAtIndex:0];
NSString *reposnseCode = [tableObject objectForKey:#"Return_Message"];
NSLog(#"%#",reposnseCode);
Problem: I can't parse data from a JSON file to a NSArray appropriately. UTF encoding is not working as expected.
My JSON looks something like:
[
{"Name":"Marcos","Address":"1234 Brasil Av. São Paulo - SP","Latitude":"-23.000","Longitude":"-46.70"},{"Name":"Mario","Address":"1000 Washignton Luiz Av. Itú SP","Latitude":"-20.0000","Longitude":"-46.000"}
]
My Objective-C code is:
NSError *error = nil;
NSURL *jsonUrl = [[NSURL alloc]initWithString:
#"http://marcosdegni.com.br/teste/webservice_teste.php"];
NSString *jsonString = [NSString stringWithContentsOfURL:jsonUrl
encoding:NSUTF8StringEncoding error:&error];
NSLog(#"jsonString: %# , Error:%#:" ,jsonString, error); //(1)
if (!error) {
NSError *error2 = nil;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error2];
NSLog(#"\n\nArray: %#" \nError:$#, jsonArray, error2); //(2)
//(*1*) This log show the content's as they are expected: note the characters ã and ú on the address fields.
//(*2*) The logs from the array and the dictionary show this charters as it's UNIX codes:\U00e and \U00fa respectively.
You can give this a try. The id json you get will be a NSArray, you can use it from there.
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray * array = json;
for (NSDictionary *dict in array) {
NSString *string = [dict objectForKey:#"Address"];
NSLog(#"%#",string);
}
From here, and I get the right result if I obtain the value of the key and log it, instead of logging the NSArray directly.
Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.
How can i parse below data:
u = "{\"userid\":\"Living123\"}";
I need to get Living123 as a string.
You can use this library to convert NSString to NSDictionary.
Import "SBJson.h" in your .m file and use following code
NSDictionary *dictionary = [u JSONValue];
NSString *userId = [dictionary valueForKey:#"userid"];
Edit
Alternatively you can use NSJSONSerialization to convert NSString to NSDictionary
NSError *e = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:u options:NSJSONReadingMutableContainers error:&e];
How to store this data in NSArray?
I'm getting JSON response in this format like this:
{
1 = USA;
4 = India;
}
I need to convert this into NSArray
If your JSON is a string, get an NSData object first:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
Then turn it into an NSDictionary using the NSJSONSerialization class:
NSError* error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
Since you said you want an NSArray, do the following:
NSArray *jsonArray = [jsonDict allValues];
Note that the order of the entries in the array is undefined, according to Apple's documentation. So if you need a particular order, you'll have to figure out a better approach.
This is JSON dictionary, First you convert this to NSDictionary from JSON.
NSDictionary *dictionary = //parse json using NSJSONSerilization
NSArray *array = [dictionary allValues];
allValues will return an array with all objects.
Try this:
NSString *jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *dictionary =[jsonString JSONValue];
NSArray *array = [dictionary allValues];
NSLog(#"Array values = %#",array);