How to extarct string between two square bracket Objective C - iphone

I have string like this:
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to get the data between two square bracket(including square bracket) and then remove all the "\" to get my final string like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
How can I do this in objective-c? thanks.

Try using JSONKit(ref) or NSJSONSerialization (ref), they will give either an NSArray or NSDictionary, depending on the structure of the JSON string.
UPDATE:
d looks like a well formed JSON string, but where is it coming from? Is it a char[] (as mentioned in the coments above), NSString, or console output?
It looks from here that your first code listing is what gets printed to the console. Printing JSON strings to the console will usually print the escape characters (\). In your other post, you are assuming every response can be parsed into an array. It would be safer to store the returned object into an id first, then check its class:
id rawData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&jsonParsingError
if ( jsonParsingError != nil ) {
// investigate the parsing error
}
else if ( [rawData isKindOfClass[NSDictionary class]] ) {
NSDictionary *dict = rawData;
// process dictionary
}
else if ( [rawData isKindOfClass[NSArray class]] ) {
NSArray *array = rawData;
// process array
}
else {
// some thing went completely wrong
}
You also do not indicate that you are checking any possible errors. Inspecting jsonParsingError will likely give clues as to what is going on.

Use nsstring method dataUsingEncoding to get a nsdata instance.
Use NSJSONSerialization
The string you wanted is same as you provided.

Since d is a string:
To remove "\" , you could this:
NSString *newString = [myString stringByReplacingOccurrencesOfString:#"\" withString:#""];
Since the square brackets are at the front and the end, maybe you could do this:
[newString removeObjectAtIndex:0];
[newString removeObjectAtIndex:[newString count]-1];
first step is to get that string according to your situation and replace myString with your string.

Only if the source string contains one [ and ] each, then...
Use componentsSeparatedByString to split the source string with [.
Use componentsSeparatedByString to split the result (objectAtIndex:0) above with ].

Related

Inserting JSON array into Sqlite iPhone

I'm getting JSON data like following in a NS array:
It seems this is not valid JSON
jsonArray:
{
d = "[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]";
}
I want to change this to valid json like this:
[
{
"Training_Code": "1234",
"Training_Duration": "2hrs",
"Training_Startdate": "14/02/201315: 00: 00",
"Training_Enddate": "14/02/201317: 00: 00",
"Trainer_ID": 1,
"Training_Location": "B-WingTrainingroom-4",
"Comments": "C#training",
"Keyword": "C#1234",
"NumberofDays": 1
},
{
"Training_Code": "4321",
"Training_Duration": "16",
"Training_Startdate": "17/02/201310: 30: 00",
"Training_Enddate": "17/02/201317: 30: 00",
"Trainer_ID": 2,
"Training_Location": "A-WingTrainingRoom-6",
"Comments": "Objective-C",
"Keyword": "Obj-C4321",
"NumberofDays": 2
}
]
Note: I do not know, from where this "d" is comming...Plaese suggest keeping this in mind.
How can I change to valid json and insert this in my Sqlite DB? Thanks.
You can always inset it as plain text. If you want to manipulate JSON Strings, I recommend this. You can transform that String into a JKArray (which is the same than an Array). After that, iterate through your array and do your DB stuff (inserting into your table...)
Am I missing something? Maybe I need more info about what you want to do...
That's a string containing an encoded JSON array. You need to use a JSON decoder (batteries included as of iOS 5) to convert it into an NSArray, then walk it:
The following (untested) code should be about right:
// Assuming jsonArray is an object with an NSString property, d...
NSData *data = [jsonArray.d dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSArray *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:err];
// Check for errors.
for (NSDictionary *row in d) {
NSString *trainingCode = [row objectForKey:#"Training_Code"];
…
// Insert into SQLite here.
}
Note that, in recent versions of Xcode, you can write row[#"Training_Code"] instead of [row objectForKey:#"Training_Code"].
Parse your json using NSJSONSerialization and insert into database by mapping keys with your columns.
NSString *str = [[NSString alloc] initWithString:#"[{\"Training_Code\":\"1234 \",\"Training_Duration\":\"2hrs \",\"Training_Startdate\":\"14/02/2013 15:00:00\",\"Training_Enddate\":\"14/02/2013 17:00:00\",\"Trainer_ID\":1,\"Training_Location\":\"B-Wing Training room-4\",\"Comments\":\"C# training\",\"Keyword\":\"C#1234\",\"NumberofDays\":1},{\"Training_Code\":\"4321 \",\"Training_Duration\":\"16 \",\"Training_Startdate\":\"17/02/2013 10:30:00\",\"Training_Enddate\":\"17/02/2013 17:30:00\",\"Trainer_ID\":2,\"Training_Location\":\"A-Wing Training Room-6\",\"Comments\":\"Objective-C\",\"Keyword\":\"Obj-C4321\",\"NumberofDays\":2}]"];
NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if(jsonError!=nil)
InfoLog(#"error: %#",jsonError);
NSArray *result = (NSArray*)allValues;
for(int i=0;i<[result count];i++)
{
NSDictionary *values = (NSDictionary*)[result objectAtIndex:i];
NSLog(#"Training_Code: %# Training_Duration: %#",[values objectForKey:#"Training_Code"],[values objectForKey:#"Training_Duration"]);
}
Now you are able to get values from NSDictionary and then simply add in your database.

Objective C Parsing JSON, Dictionary returns a NSCFString instead of NSArray

What I'm trying to do is take a JSON feed and then loop through the results. However I keep getting a string instead of an array when I get the object from the dictionary. Any ideas on what I'm doing wrong?
Here's the JSON:
[
{
"_id": "4f6d9a7c1d0b4900010007ee",
"geo_triggers": [
{
"_id": "4fc3e5fdc7234e0001000002",
"location": [1,1],
"longitude": "1",
"latitude": "1",
"radius": 1,
"location_name": "Test 1"
},
{
"_id": "4fc61f3762f53f0001000043",
"location": [-71.057673,42.355395],
"longitude": "-71.057673",
"latitude": "42.355395",
"radius": 1000,
"location_name": "Test2"
}
]
}
]
Here's the Objective C Code:
const char* className = class_getName([result class]);
NSLog(#"Result is a: %s", className);
NSLog(#"%#", result); //string
NSArray* json = [result objectForKey:#"result"]; //should be an array of dictionaries
NSLog(#"JSON Output: %#", json);
const char* className1 = class_getName([json class]);
NSLog(#"yourObject is a: %s", className1);
And here's the output:
Result is a: __NSDictionaryI
2012-10-10 17:15:15.165 App[12980:19d03] {
result = "[{\"_id\":\"4f6d9a7c1d0b4900010007ee\",\"geo_triggers\":[{\"_id\":\"4fc3e5fdc7234e0001000002\",\"location\":[1.0,1.0],\"longitude\":\"1\",\"latitude\":\"1\",\"radius\":1,\"location_name\":\"Test 1\"},{\"_id\":\"4fc61f3762f53f0001000043\",\"location\":[-71.057673,42.355395],\"longitude\":\"-71.057673\",\"latitude\":\"42.355395\",\"radius\":1000,\"location_name\":\"Test2\"}]}]";
}
2012-10-10 17:15:15.166 App[12980:19d03] JSON Output: [{"_id":"4f6d9a7c1d0b4900010007ee","geo_triggers":[{"_id":"4fc3e5fdc7234e0001000002","location":[1.0,1.0],"longitude":"1","latitude":"1","radius":1,"location_name":"Test 1"},{"_id":"4fc61f3762f53f0001000043","location":[-71.057673,42.355395],"longitude":"-71.057673","latitude":"42.355395","radius":1000,"location_name":"Test2"}]}]
2012-10-10 17:15:15.166 App[12980:19d03] yourObject is a: __NSCFString
2012-10-10 17:15:15.166 App[12980:19d03] -[__NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0xb331800
Your result variable points to a dictionary. The dictionary contains one key. That key is #"result". The value for that key is a string, #"[{\"_id\":\"4f6d9a7c1d0b4900010....
In other words, you haven't really deserialized your JSON. You need to take the value for key result and run it through a JSON deserializer.
First need to decode the result. The above is JSON so I would suggest doing this
If you don't already have it download JSONKit.h and include it in your project
Then you can either do
NSString* json = [result JSONString]; to see the output
OR
something like id jsonDict = [[JSONDecoder decoder] objectWithData:responseData];
After that you can do [jsonDict objectForKey:#"_id"]; ///etc

Json Parsing issue iOS : missing "

I got a big issue when trying to parse json data in xcode. I have actually tried with two different parser and it still returns me a wrong json. Could anyone help in that ?
The string to parse (called jsonResp) is equal to :
{
"error":false,
"errorMessage":null,
"debugMessage":null,
"count":1,
"list":"links",
"data":[
{
"date":"Jeudi \u00e0 00:00:00",
"type":"friend",
"picture":"http://graph.facebook.com/22222222/picture? type=square",
"name":"Etouda Gaudo",
"ink_id":"1",
"chat_id":"1",
"count":"1",
"last_message":"CoUcou"
}
]
}
the string to parse is equal to :
NSData *jsonData = [jsonResp dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(#"dictionary %#", dictionary);
and then I got the following result for the NSLog of dictionary :
dictionary {
count = 1;
data = (
{
"chat_id" = 1;
count = 1;
date = "Jeudi \U00e0 00:00:00";
"ink_id" = 1;
"last_message" = CoUcou;
name = "Test name";
picture = "http://graph.facebook.com/22222222/picture?type=square";
type = friend;
}
);
debugMessage = "<null>";
error = 0;
errorMessage = "<null>";
list = links;
}
I can't figure out why the " are missing...
Does anyone have a solution.
Thanks in advance.
NSLog is just a print representation for developers to view, it is the result of the description method being called on a class instance. Quotes are only added where the item might be ambitious without them such as a string with an embedded space. To verify that the JSON was parsed correctly validate it with code.
You are deserializing the JSON into an NSDictionary, which doesn't have to have quotes around it's property names, unlike JSON. Your parser is working correctly, but the NSLog of an NSDictionary won't show up exactly the same as the original JSON would.

Error in json parsing while converting response into NSDictionary

AM getting below error while converting json response into NSdictionary in json parsing...
ERROR:-JSONValue failed. Error trace is: (
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 UserInfo=0x4d38270 "Unrecognised leading character"
)
any suggestion...
You most likely have the same issue as me... The returning data is in JSONP format instead of pure JSON. In other words you will be dealing with something like
functionCall({"Name": "Foo", "Id" : 1234, "Rank": 7});
instead of just
{"Name": "Foo", "Id" : 1234, "Rank": 7}
More info here
You'll need to strip the function and parentheses from the string before parsing it through the JSON Framework. You can do that with the following Regular Expression (spaced out to make it easier to see):
\w+ \s? \( ( \{ .* \} ) \}
And the script to write this is:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\w+\\s?\\((\\{.*\\})\\)"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex replaceMatchesInString:resultString
options:0
range:NSMakeRange(0, [resultString length])
withTemplate:#"$1"];
NSLog(#"resultString = %#", resultString);
NSLog(#"converted = %#", [resultString JSONValue]);
where resultString is the response from the url request... It has to be stored as an NSMutableString in order for the regex to update it.
actually am not creating the json object by using api am retrieving it..
now i found the reason for that error. am not giving valid json object to covert into nsdictionary...So for getting valid json object we have to produce valid url to retrieve json object.
thanks for your suggestion...

NSString: EOL and rangeOfString issues

Could someone please tell me if I am missing something here... I am trying to parse individual JSON objects out of a data stream. The data stream is buffered in a regular NSString, and the individual JSON objects are delineated by a EOL marker.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSString *tmp = [dataBuffer stringByReplacingOccurrencesOfString:#"\n" withString:#"NEWLINE"];
NSLog(#"%#", tmp);
}
The code above outputs "...}NEWLINE{..." as expected. But if I change the #"\n" in the if-statement above to #"}\n", I get nothing.
Why don't you use - (NSArray *)componentsSeparatedByString:(NSString *)separator? You can give it a separator of #"\n" and the result will be a convenient array of strings representing your individual JSON strings which you can then iterate over.
if([dataBuffer rangeOfString:#"\n"].location != NSNotFound) {
NSArray* JSONstrings = [dataBuffer componentsSeparatedByString:#"\n"];
for(NSString* oneString in JSONstrings)
{
// here's where you process individual JSON strings
}
}
If you do mess with the terminating '}' you could make the JSON data invalid. Just break it up and pass it to the JSON library. There could easily be a trailing space after the '}' that is causing the problem you are observing.