Parsing of JSON array returning blank array - ios

I have an array which is of below kind.
{"Hotweeks":[{"Image":"http://www.example.com/wp-content/uploads/0970E01L.jpg","Description":"Ocean Shores, WA","PostTitle":"Windjammer Condominiums"},
{"Image":"","Description":"","PostTitle":"0970O01L"},
{"Image":"","Description":"","PostTitle":"0970I08L"},
{"Image":"","Description":"","PostTitle":"0970I06L"},
{"Image":"","Description":"","PostTitle":"0970I04L"},
{"Image":"","Description":"","PostTitle":"0970i03L"},
{"Image":"","Description":"","PostTitle":"0970I02L"},
{"Image":"","Description":"","PostTitle":"0970I01L"},
{"Image":"","Description":"","PostTitle":"0970E02L"},
{"Image":"","Description":"","PostTitle":"0970E01L"},
{"Image":"http://www.example.com/wp-content/uploads/0936E01L.jpg","Description":"Manson, WA","PostTitle":"Wapato Point"},
{"Image":"","Description":"","PostTitle":"0936O05L"},
{"Image":"","Description":"","PostTitle":"0936O04L"},
{"Image":"","Description":"","PostTitle":"0936O03L"},
{"Image":"","Description":"","PostTitle":"0936O02L"},
{"Image":"","Description":"","PostTitle":"0936O01L"},
{"Image":"","Description":"","PostTitle":"0936I01L"},
{"Image":"","Description":"","PostTitle":"0936E03L"},
{"Image":"","Description":"","PostTitle":"0936E02L"},
{"Image":"","Description":"","PostTitle":"0936E01L"}]}
Which I am trying to parse using the below code.
NSArray *array = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);
This is returning null in Nslog.

…"Description":"Ocean Shores, WA,"PostTitle":…
is missing a " after Ocean Shores, WA. It should be
…"Description":"Ocean Shores, WA","PostTitle":…
Use a JSON validator to check for this type of thing. There are many to pick from. I use the Chrome apps JSON Lint and JSON Editor.

The top level of your Json file is an object, not an array (it doesn't start with '['). That being said, if you check array's type like this: NSLog("%#", [array class] you'll probably see it's a NSDictionary.
To get the array you can do this:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSArray *array = jsonDict[#"Hotweeks"];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);

Related

How assign value to a JSON string?

I get this JSON object from my web service
0: {
Username: "John"
Password: "12345"
Position: "Admin"
Job: "Developer"
ResourceJobId: 1
}
When I try to assign a value, for example, to Username JSON string, I get a semantic error:
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
for (NSDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString ;
I know how get the JSON object with NSJSONSerialization class, but my target is how assign the value #"" to the JSON object.
So how can I assign the value #"" to the Username JSON string?
While you are trying to fetched dictionary from array. it is not mutable dictionary so you need to created NSMutableDictionary while fetching data from Array. following code will help you to change username.
for (NSMutableDictionary *dictionary in array)
{
NSMutableDictionary* dictTemp = [NSMutableDictionary dictionaryWithDictionary:dictionary];
[dictTemp setObject:usernameString forKey#"Username"];
[_arrayList replaceObjectAtIndex:index withObject:dictTemp];
}
Well your assignment operation is written wrong, it should be indeed like this:
If you need to get value from dictionary
usernameString = [dictionary objectForKey:#"Username"];
If you want to set a value to your dictionary, first of all your dictionary should be NSMutableDictionary
[dictionary setObject:usernameString forKey:#"Username"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error;
id obj = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
if(!error && [obj isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)obj;
Booking *booking = nil;
for (NSMutableDictionary *dictionary in array) {
NSString *usernameString = #"";
//this line of code gives me an error: Expression is not assignable
[dictionary objectForKey:#"Username"] = usernameString;
Yes, is a compiler error
You need to have a mutabledictionary inorder to change the value. Try this
for (NSDictionary *dictionary in array) {
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionary];
NSString *usernameString = #"";
[mutableDictionary setValue:#"" forKey:usernameString];
}
Even the answers are correct, I want to add that you do not have to do this your own. NSJSONSerialization already has a solution for that. Simply pass as options one of these:
NSJSONReadingMutableContainers = (1UL << 0),
NSJSONReadingMutableLeaves = (1UL << 1),
when reading the JSON.

Can't iterate JSON string from asp.net WCF service in Xcode

I am new to objective-c but I am trying to render out a simple UItableview, filling it with data from my REST service coded in asp.net. The service takes data from SPs run on SQL servicer and using the JSONSerailzer class spits out a JSON string. I have verified it is a valid JSON string by pasting the output to an online JSON viewer.
Example as follows (This is exactly how my service returns it):
{"d":"[{\"callref\":12345,\"user\":\"foo\",\"name\":\"bar\"},{\"callref\":54321,\"user\":\"bar\",\"name\":\"foo\"}]"}
I can get the data in to objective-c fine via:
id result = [NSJSONSerialization JSONObjectWithData:webData options:kNilOptions error:&error];
However when I try to step into this result either by casting as NSDictionary or NSArray but the result always ends up as NSCFString and because of that it crashes my code when I try to enter a for loop.
NSArray *allItems = [result objectForKey:#"d"];
for (int i=0; i<allItems.count; ++i) {
NSDictionary *item = [allItems objectAtIndex:i];
NSString *callref=[item objectForKey:#"callref"];
NSString *user=[item objectForKey:#"user"];
NSString *name=[item objectForKey:#"name"];
}
What am I missing here? Any help greatly appreciated! Thanks in advance.
The JSON being returned from the server is not what you expect it to be, by the look of it.
It's a dictionary (see the outer { and }), however it contains a key of "d" and a string value of "[{\"callref\" ..." (note the first double-quote and the escaped inner double-quotes).
So first job is to fix the server, which is off-topic to your question.
After that, it should be as simple as:
NSDictionary* result = [NSJSONSerialization JSONObjectWithData:webData
options:kNilOptions
error:&error];
NSArray *keys = [result allKeys];
for (NSString *key in keys) {
NSArray *array = result[key];
for (NSDictionary *item in array) {
NSString *callref = item[#"callref"];
NSString *user = item[#"user"];
NSString *name = item[#"name"];
}
}

iOS enumerate json remove objectkey

I'm struck how to enumerate JSON by remove first object in iOS programming as below
From
[{"001": {"name":"test", "url":"test"},"002":{"name":"test1", "url":"test1"},"003":{"name":"test2", "url":"test2"}}]
to
[ {"name":"test", "url":"test"},{"name":"test1", "url":"test1"},{"name":"test2", "url":"test2"}]
Pls help to recommend me or suggestion coding.
Thank you.
Try this,
NSArray *jsonArray = //parsedJsonArray
NSDictionary *values = [jsonArray objectAtIndex:0];
NSArray *valuesArray = [values allValues];
And the valuesArray will contain the data in format,
[ {"name":"test", "url":"test"},
{"name":"test1", "url":"test1"}, {"name":"test2", "url":"test2"}]
You can easily convert a json string to a NSMutableArray :
NSError *error;
// Get a NSMutableArray from the json string
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
// Remove the first object
[arrayResult removeObject:[arrayResult firstObject]];
jsonDataArray1=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"001"]];
jsonDataArray2=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"002"]];
jsonDataArray3=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"003"]];
jsonDataArrayFinal=[[NSMutableArray alloc]initWithObjects:jsonDataArray1,jsonDataArray2,jsonDataArray3 nil];
initialize all above arrays in viedidload

Cant access serialized JSON data (NSJSONSerialization)

I get this JSON from a web service:
{
"Respons": [{
"status": "101",
"uid": "0"
}]
}
I have tried to access the data with the following:
NSError* error;
//Response is a NSArray declared in header file.
self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *test = [[self.response objectAtIndex:0] objectForKey:#"status"]; //[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSString *test = [[self.response objectForKey:#"status"] objectAtIndex:0]; //(null)
But none of them work, if i NSLog the NSArray holding the serialized data, this i what i get:
{
Respons = (
{
status = 105;
uid = 0;
}
);
}
How do i access the data?
Your JSON represents a dictionary, for whom the value associated with the Respons key is an array. And that array has a single object, itself a dictionary. And that dictionary has two keys, status and uid.
So, for example, if you wanted to extract the status, I believe you need:
NSArray *array = [self.response objectForKey:#"Respons"];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *status = [dictionary objectForKey:#"status"];
Or, in latest versions of the compiler:
NSArray *array = self.response[#"Respons"];
NSDictionary *dictionary = array[0];
NSString *status = dictionary[#"status"];
Or, more concisely:
NSString *status = self.response[#"Respons"][0][#"status"];
Your top level object isn't an array, it's a dictionary. You can easily bypass this and add the contents of that key to your array.
self.response = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] objectForKey:#"Respons"];

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources