NSMutableDictionary representation for JSON - iphone

I have one genuine question which I am facing at this point and I am sure someone might be able to help me.
I have a JSON Post which looks like:
{
"CustomerAccount":{
"CustomerUID":"String content",
"UserName":"String content",
"Password":"String content",
"OldPassword":"String content",
"Email":"String content",
"QuestionUID":2147483647,
"QuestionAnswer":"String content",
"EAlerts":true
}
}
Now I have a dictionay which set's value of CustomerUID, UserName, etc.. Now if I want to bind a upper level to bind all that to CustomerAccount and send as my JSONRepresentation, is there any easier way than actually creating a new dictionary and setting a value of key "CustomerAccount" in this example? I am sure there might be a better way of doing that.
Thanks.

Not entirely sure I follow, but is this what you want maybe:
NSDictionary *dictA = <dictionary_with_customeruid_etc>;
NSDictionary *customerAccountDict = [NSDictionary dictionaryWithObjectsAndKeys:dictA, #"CustomerAccount", nil];
But I'm not sure I follow your question entirely so maybe you want something else. Please let us know a bit more about what you're trying to do.

I don't really understand your question but ill give it a try.
You can easily parse the JSON string to a NSDictionary using JSONKit https://github.com/johnezang/JSONKit
JSONKit is a very fast and lightweight library and you can parse the string and get the wanted value like this:
NSDictionary *dict = [jsonString objectFromJSONString];
NSString *value = [dict valueForKey:#"key"];
To actually set a value in your JSON string you should use rangeOfString: .location to get the range if the existing value then replaceOccurenciesOfString:[jsonString substringWithRange:NSMakeRange(loc,len)] withString:VALUE.

Related

NSDictionary id key value

I recently try to change the Json library in my applicaiton from SBJson to the NSJSONSerialization.
When I do this job, I find there are some key value that I can not get out.
Here is an example of the NSDictionary I get after NSJSONSerialization:
{
id = 4028;
"novel_author" = "XYZ";
"novel_pub" = "ABC";
"novel_title" = "DATE LIVE";
updatedate = "2013-01-13 22:31:13";
"vol_click" = 7563;
}
The original Json data string is:
{
"id":"4028",
"vol_click":"7563",
"updatedate":"2013-01-13 22:31:13",
"novel_author":"XYZ",
"novel_pub":"ABC",
"novel_title":"DATE LIVE"
}
I can not get the value of the key "id" out.
[NSDictionary objectForKey#"id"] is useless.
Is there anyone have idea how to get the value out?
As you can tell by the output of what looks like NSLog("%#", dict);, the JSON deserialization process works fine.
The dictionary contains a key called "id", so [dict objectForKey:#"id"] should also work fine.
I can only conclude that this isn't the actual cause of the trouble you're having.
Either of these should work:
[yourDictName valueForKey:#"id"]
[yourDictName objectForKey:#"id"]
If you can see the value using NSLog to display the dictionary, then it is there. Beyond that, make sure your object is not getting nil'd or released or freed.

SBJson parsing help iphone

im currently trying to parse some json data on the iphone.
I have been trawling the web for examples, but none seem to suit my purpose, i am using SBJson.
What I want is to be able to get an NSArray of Titles, Artisits, Status, etc. so that I can display them on a table view. Any help would be great, so far all i get is an array of "Values".
JSON = {"values":
[
{"Status":"N", "Filename":"RD207T04", "Title":"Simple Man (Explicit)", "Artist":"DIAFRIX F/DANIEL MERRIWE", "Release":"May11"},
{"Status":"N", "Filename":"CR221T27", "Title":"Midnight City", "Artist":"M83", "Release":"Dec11"},
{"Status":"N", "Filename":"ED211T03", "Title":"I\"ll Be Your Man", "Artist":"JAMES BLUNT", "Release":"Jul11"}
]}
You don't want an array of titles, artists, etc. You want the array of NSDictionarys represented by the values key. Then you can do:
cell.textLabel.text = [[valuesArray objectAtIndex:indexPath.row]valueForKey:#"Title"]];
inside your cellForRowAtIndexPath: delegate method. If you do not have this already, this is how to get that array:
NSArray *valuesArray = [[myJsonString JSONValue]objectForKey:#"values"];
Thanks mate, I was definately over complicating things:
The end code was this:
NSArray *valuesArray = [[playlist JSONValue] objectForKey:#"values"];
NSString *test = [[valuesArray objectAtIndex:0]valueForKey:#"Title"];
NSLog(#"test = %#", test);
Now all I have to do is iterate through the set :)

Parsing XML Inner XML tags Objective-C

I would like to create an NSDictionary or (NSArray) full of NSDictionary objects for each station in the following XML:
<stations lastUpdate="1328986911319" version="2.0">
<station>
<id>1</id>
<name>River Street , Clerkenwell</name>
<terminalName>001023</terminalName>
<lat>51.52916347</lat>
<long>-0.109970527</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1278947280000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>7</nbEmptyDocks>
<nbDocks>19</nbDocks>
</station>
... more...
<station>
<id>260</id>
<name>Broadwick Street, Soho</name>
<terminalName>003489</terminalName>
<lat>51.5136846</lat>
<long>-0.135580879</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1279711020000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>4</nbEmptyDocks>
<nbDocks>18</nbDocks>
</station>
...
</stations>
What's the best way to achieve this? Right now I have an NSDictionary with one object and one key - "stations", but I want the NSDictionary (or NSArray) of NSDictionarys.
I'm using an XML parser by Troy Brant - http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
I'm guessing it's going to involve some looping of some sort but I'm not really sure how to approach this problem. Any help or pointers in the right direction would be much appreciated.
Thanks.
I also use the XMLReader it is very easy to understand
I have looked at your xml, and I am assuming you wanted to use the array of station tags.
Here is my solution:
NSDictionary *dictXML= [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
NSArray *arrStation = [[dictXML objectForKey:#"stations"] objectForKey:#"station"];//this would return the array of station dictionaries
Now that you have the array of station tags you can do what you want for example displaying all id:
for(int i=0;i<[arrStation count];i++){
NSDictionary *aStation = [arrStation objectAtIndex:i];
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
also you can write less code using the fast enumeration loop:
for(NSDictionary *aStation in arrStation){
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
hope that helps :)
The best way would be to create subclasses of NSObject that map to each tag. That would be way more cleaner than using Dictionaries and Arrays.

iPhone SDK: Problems Parsing JSON

I'm using the SBJSONParser for my iphone app. Up to now, i've been parsing simple json strings such as: ["Business1","Business2"]
I'm now using PHP to get both the business name and business ID from the database within the same json string, so my PHP is giving me a result like this:
{"business_1A" : "ABC_1","businees_2A": "ABC_2" }
Here's the code that i'm currently using to process the first JSON output which works fine:
businessNames is an NSMutableArray in the following code.
NSString *businessNamesJSON = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"businessNamesJSON.php"]]];
SBJsonParser *parser = [[SBJsonParser alloc]init];
businessNames = [[parser objectWithString:businessNamesJSON error:nil]copy];
Basically, I want to split the second JSON output so that I can have two separate NSMutableArrays, one which contains the business Names and the other which holds the IDs.
How do I extract or split the second JSON output so I can do this?
Thanks in advance.
Hy there
Let me take a step back. Since you have a list of companies wouldn't it be a better way to represent your data with an array in json like so:
[
{
"identifier": "ABC_1",
"name": "business_1A"
},
{
"identifier": "ABC_2",
"name": "businees_2A"
}
]
I believe this would make the parsing of the data easier for you and it would allow you to add more attributes in the future.
So once you have this structure you can parse the json data and then loop over the entries and extract the values for the keys identifier and name (in this case) respectively.
{"business_1A" : "ABC_1","businees_2A": "ABC_2" } defined an object in JSON terms, which will be returned by any sane JSON parser as an NSDictionary in Objective-C, being a collection of mappings from one object to another.
You seem then to want all the keys and all the values separately. In that case you can just get them from the NSDictionary:
SBJsonParser *parser = [[SBJsonParser alloc] init];
businessNamesDictionary = [parser objectWithString:businessNamesJSON error:nil];
NSLog(#"names: %#", [businessNamesDictionary allKeys]);
NSLog(#"values: %#", [businessNamesDictionary allValues]);
Take mutableCopys if you want them. Use objectsForKeys:notFoundMarker: if you want to guarantee that the values come out in the same order as the keys — the order of each is explicitly undefined in the documentation so don't rely on whatever order you happen to get on whichever version of the OS you happen to test against.

Get objects from a NSDictionary

I get from an URL this result :
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
it looks like this :
[{"modele":"Audi TT Coup\u00e9 2.0 TFSI","modele_annee":null,"annee":"2007","cilindre":"4 cyl","boite":"BVM","transmision":"Traction","carburant":"ES"},
{"modele":"Audi TT Coup\u00e9 2.0 TFSI","modele_annee":null,"annee":"2007","cilindre":"4 cyl","boite":"BVM","transmision":"Traction","carburant":"ES"}]
So it contains 2 dictionaries. I need to take the objects from all the keys from this result. How can I do this?
I tried this : NSDictionary vehiculesPossedeDictionary=(NSDictionary *)result;
and then this : [vehiculesPossedeDictinary objectForKey:#"modele"]; but this is not working.
Please help me... Thanks in advance
What you have is a JSON string which describes an "array" containing two "objects". This needs to be converted to Objective-C objects using a JSON parser, and when converted will be an NSArray containing two NSDictionarys.
You aren't going to be able to get your dictionary directly from a string of JSON. You are going to have to going to have to run it through a JSON parser first.
At this point, there is not one build into the iOS SDK, so you will have to download a third-party tool and include it in your project.
There are a number of different JSON parser, include TouchJSON, YAJL, etc. that you can find and compare. Personally, I am using JSONKit.
#MatthewGillingham suggests JSONKit. I imagine it does fine, but I've always used its competitor json-framework. No real reason, I just found it first and learned it first. I do think its interface is somewhat simpler, but plenty of people do fine with JSONKit too.
Using json-framework:
require JSON.h
...and then
NSString *myJsonString = #"[{'whatever': 'this contains'}, {'whatever', 'more content'}]";
NSArray *data = [myJsonString JSONValue];
foreach (NSDictionary *item in data) {
NSString *val = [item objectForKey:#"whatever"];
//val will contain "this contains" on the first time through
//this loop, then "more content" the second time.
}
If you have array of dictionary just assign objects in array to dictionary like
NSDictionary *dictionary = [array objectAtIndes:0];
and then use this dictionary to get values.