iOS: Parsing dictionaries from a string into NSMutableDictionary / NSMutableArray - ios

Is there a fast way to parse dictionaries in iOS from a sting, with the format:
property1: value1
property2: [ property3: value3 ; property4: [property5: value5] ]
property6: "and so on"
The string would contain something like:
NSString *str = #"property1: value1 property2: [ property3: value3 ; property4: [property5: value5]] property6: "and so on" ";
and would generate a root NSMutableDictionary / NSMutableArray element, containing additional
NSMutableDictionary / NSMutableArray elements
Thanks in advance

why not using json format ?
replace this with this
[ {
] }
; ,
and you will be able to use jsonparser : NSJSONSerialization

No. That isn't any standard format. It looks like a bizarro version of JSON. If you want to parse this format, you'll need to either find some third-party parser or wrote one yourself.

Your JSON string is invalid. Please use http://jsonlint.com to verity if your JSON string is valid or not. Now, given your JSON is valid, this is how you can read string JSON into a NSDictionary:
NSString *strData = #"{\"property1\":\"value1\",\"property2\":{\"property3\":\"value3\",\"property4\":\"value4\"}}";
NSData *data = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", json);

Related

I want to convert a specific string to json

server response
-> NSString : { key1 = value1 }{ key2 = value2 }{ key3 = value3 }
How do I convert it to json?
What should I do?
I think what you are looking for is something like this , but im not suer if you can use = isntead of :
NSString *stringValue =#"[{ \"Key1\":\"Value1\" },{ \"Key2\":\"Value2\" },{ \"Key3\":\"Value3\" }]";
NSLog(#"StringValues from Server=%#", stringValue);
// Convert to JSON object:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[stringValue dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:NULL];
NSLog(#"jsonObject=%#", jsonObject);
If this is not what you want try to give us some code and explain how you want it done

iOS JSON Parsing, Format Issues

So I was working on a project that required me to work with some JSON, I was running into a few issues regarding the best way of representing things. First of, this is how the JSON looks:
"phoneList": [
{
"phoneReason": "End of Contract",
"phoneType": [
{
"id": 5,
"phoneType": "Android Smartphone"
}
]
}
]
I want to know the most appropriate way of representing this.
For example, I do know that that my phoneReason will just be a simple NSString while my phoneType is actually a NSArray. However,I wasn't sure how to represent a)the id, I know this is an integer, but should this be an NSInteger or an NSNumber and b)could someone point me in the direction of some sample code where I can understand how to model a dictionary object containing an integer and a string and also where I can understand how to model an array of dictionaries.
My other question is also similar in that say I'm actually posting something, how do I model this, specifically say for like dictionary type (JSON Curly Brace)objects that contain a number/integer and a string.
For example, this is the JSON I'm trying to model and then do something like this:
"phoneReason": "Upgrade",
"phoneInfo": {
"id": "2"
},
//And then I want to pass ID
-(void) createOurRequest:(NSNumber *)id {
NSDictionary *myDictionary = #{
#"phoneReason" : [NSString stringWithFormat:#"%i", s elf.dat.reason],
//How do I then represent the phoneInfo element exactly?
};
Sorry, for the clumsy question, would really appreciate any guidance on modeling JSON in iOS or just generally.
I'm assuming you're asking questions a) and b), and also how to model a JSON.
a) The unfortunate thing with Obj-C is that all collection elements have to be objects. Integers are value types, so they will need to be converted to NSNumbers to work. However, if you're parsing a JSON string, the builtin JSON parser does it for you. I'll describe it below.
b) The model is based on the JSON. You describe the object collection and the parser will determine the model for you. In your example, you would have a NSDictionary<NSString *: NSArray<NSDictionary<NSString *: id>*>*>. The innermost element has value of id because you can either have an NSString ("End of Contract") or an NSArray ("phoneType": [ { "id": 5, "phoneType": "Android Smartphone" } ])
Of course, the model is defined by your JSON, so if you run it through a parser, you get a structured object. You can access each element based on your model (object[#"phoneList"][#"phoneReason"]).
The class method to use is:
+ (id)JSONObjectWithData:(NSData *)data
options:(NSJSONReadingOptions)opt
error:(NSError **)error
Where you pass it a NSData representation of your string, options (or 0), and a NSError pointer (error*). You get back a parsed JSON with the proper structure you defined.
NSDictionary *parsedJSONObject = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL
I have no options to use and I know there will be no error, so I pass nothing for those parameters. The resulting object will be in whatever structure your JSON is.
Using the objects and the json layout you provided in your first example, this is how I would go about creating the dictionaries and arrays to get the json in the format you specified. Hopefully this helps make it a little clearer for you.
// example constructor method
-(void) jsonStringWithPhoneReason:(NSString*)reason phoneId:(NSInteger)phoneId phoneType:(NSString*)phoneType
{
// create device detail dictionary
NSDictionary *deviceOneDetail = #{
#"id" : #(phoneId), // <- set phone id as NSNumber
#"phoneType" : phoneType // <- set your string phone type
};
// create device dictionary
NSDictionary *deviceOne = #{
#"phoneReason" : reason, // <- set your phone reason string
#"phoneType" : #[deviceOneDetail] // <- set your phone type dictionary within an array
};
// create phone list dictionary with any device dictionaries you want to add
NSDictionary *phoneListDict = #{
#"phoneList" : #[
deviceOne, // <- add your device to the phone list array of dictionaries
// deviceTwo...
]
};
NSString *jsonString = [self convertToJsonString:phoneListDict]; // <- convert the dictionary into a json string and use however you wish
// your json string should now look like this assuming you pass 'End of Contract', 5 & 'Android Smartphone' as arguments to this method
// {"phoneList":[{"phoneReason":"End of Contract","phoneType":[{"id":5,"phoneType":"Android Smartphone"}]}]}
}
-(NSString*) convertToJsonString:(NSDictionary*)dictionary
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (error)
{
NSString *errorDesc = [NSString stringWithFormat:#"Error creating json data from dictionary: %#", error.localizedDescription];
NSLog(#"ERROR: %#", errorDesc);
jsonData = nil;
return nil;
}
NSString *returnString = nil;
if(jsonData != nil)
{
returnString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return returnString;
}

Convert String(already formatted) to an Array of NSDictionary

I have this String already formatted as a [[String:AnyObject]], however I can't retrieve the information out of it nor couldn't find a way to convert it to a dictionary.
[ [name: Laura, age:33, gender: female], [name: James, age:25,
gender:male] ]
What can be done to convert this string into a dictionary?
Your formatted string must be well formatted as an json, then you can use the next code:
NSString* str=#"[ {\"name\": \"Laura\", \"age\":33, \"gender\": \"female\"}, {\"name\": \"James\", \"age\":25, \"gender\":\"male\"} ]";
NSData* data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSArray* jsonArr=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",jsonArr);

Converting JSON string into object

I am trying to convert a JSON string into an object in Objective C using the code:
NSString *jsonString = (NSString *) responseObject;
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
The value of jsonString is
"[{\"Date\": \"12-01-2015\", \"Time\": \"7:00 am\", \"Title\":
\"First Car Service\", \"Details\": \"This was the first car
service ever done\"}]"
But the value of json is always nil. How do I convert the jsonString into a NSArray ?
My (third) bet: your json string isn't correct. If it contains the leading and trailing quotes strip them. Replaced the \" with ".
better: make the server or other json source send correct json.
From the error, it may be that your string is not formatted correctly, probably due to the quotes.
You should also make sure that after you have formatted the string, then you check the array has objects.
NSLog(#"JSON Details: %#", json[0][#"Details"]);

JSon array to core data entity

I have a cuestion about parsing a Json strings.
If i'm getting a string like:
[["AR","Argentina","flag_of_argentina","en","F","1"],
["AU","Australia","flag_of_‌​australia","en","B","4"]]
How can i save this string into an entity when normally i see Jsons that have something like this:
(
(
"Group_id": 1,
"Date" : "2014-04-08",
"Hour" : "18:00:00",
"Location":"Guayaquil, Ecuador",
"State" : A
),
...
If i have to make an array or something else to store it to the entity in core data how can i do it?
I hope my question is well made ​​and I appreciate your help. Thank you very much.
Cocoa Touch provides a built in class that helps you serialize this data. It's called NSJSONSerialization.
So, that looks to me like you have arrays within an array. First you're going to want to convert the NSString to NSData:
NSData *JSONdata = [yourJSONString dataUsingEncoding:NSUTF8StringEncoding];
Then serialize it into an array:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:JSONdata options:NSJSONReadingMutableContainers error:&error];
Then you can access any subarray by writing:
NSArray *countryData = [JSONArray objectAtIndex:i];
And from there you can access the data that you need.
~
As for building JSON Data, you'll need to construct an NSMutableDictionary and populate it accordingly. Once you have that, use the same class NSJSONSerialization to convert it to a JSON string.

Resources