Json Data converted to Json string but not in Json Dictionary - iphone

This question has been asked so many times but using the same code I am getting things work.
I have used below code to generate Json Dictionary and Json string.It successfully creates json string but not json dictionary.
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *strJsonRequest = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dicJsonRequest = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&convertError];
NSLog(#"\n dicjson : %# \n json string : %# \n error : %#",dicJsonRequest,strJsonRequest,convertError.localizedDescription);
This metods I am using to pass data and this needs NSDictionary
- (void)postPath:(NSString *)path
parameters:(NSDictionary *)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
If I create NSDictionary using JsonString created here then it gets converted to different format that is not being accepted at webservice end
NSDictionary *WSCALL = [NSDictionary dictionaryWithObjectsAndKeys:strJsonRequest,"Post", nil];
NSLog(#"WSCALL : %#",WSCALL);
output :
WSCALL : {
Post = "{\n \"email\" : \"test#test.com\",\n \"password\" : \"test\",\n \"name\" : \"abcd\",\n ";
}
EDIT
What i can conclude here is webservice needs the same json string created but without this "\n" and \"email\" (FALSE) -> "email"(TRUE)
But i am not able to replace "\n" because it is adding when i set value for key in dictionary.
With this I am getting output as
dicjson : {
email = "test#test.com";
name = abcd;
password = test;
}
json string : {
"email" : "test#test.com",
"name" : "abcd",
"password" : "test"
}
error : (null)

Well there is no error in what you are doing and the log says clearly you are getting a NSDictionary, and If you try to log an NSDictionary it is obvious you get a json string response.See this line
NSLog(#"\n dicjson : %# \n json string : %# \n error : %#",dicJsonRequest,strJsonRequest,convertError.localizedDescription);
Here the NDDictionary contains the value correctly since the log shows
dicjson : {
email = "test#test.com";
name = abcd;
password = test;
}
So you have a valid dictionary in hand.Just do the remaining coding

Related

regex to detect a pattern in a JSON string

I have a string like this
"Settings" : { "UserId" : 3, "UserToken" : "4578965235874158", "SecurityCode" : "111", "Password" : "12345", "UserPhone" : "555-555-1531", "drop" : -1, "UserLastName" : "Smith" }
I need a regular expression pattern to find the value of the "UserToken"( in this example 4578965235874158)
Sorry if this is a "Give me code" question, but I never worked with regular expressions and I do not have much time to learn and try to do it myself.
Thanks for help.
Additional notes:
I will use it in objective-C for an iPhone application. I don't know if that affect anything but just in case.
EDIT'
The pattern is: the key is always "UserToken" followed by a space then by a : then another space after that comes the value inside double Quotes ". I would like to get this value.
Since it's a json format you don't really need to parse it with regex, but if you need to, this can be a solution:
(?<="UserToken"\s:\s")\d+
I would have converted it and access all information I need like:
NSString *str = #"\"Settings\" : { \"UserId\" : 3, \"UserToken\" : \"4578965235874158\", \"SecurityCode\" : \"111\", \"Password\" : \"12345\", \"UserPhone\" : \"555-555-1531\", \"drop\" : -1, \"UserLastName\" : \"Smith\" }";
//NSDictionary *jsonDict = [str JSONValue];
NSError *error;
NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
than all information are stored on the results NSDictionary, just have to do something like: [results valueForKey:(NSString *)] or [results objectForKey::(NSString *)]

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.

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.

Decoding JSON with JSONKit gives error

I have the following JSON that validates as valid JSON..
{"flights":[{"flight":{"flightno":"BAW699","timestamp":"2011-03-22 07:06:02","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW706","timestamp":"2011-03-21 19:08:02","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW5MG","timestamp":"2011-03-21 16:33:02","route":"LEMG-EGLL"}},{"flight":{"flightno":"BAW3AG","timestamp":"2011-03-21 11:25:02","route":"EGLL-LEMG"}},{"flight":{"flightno":"BAW5EB","timestamp":"2011-03-20 19:18:02","route":"EGLL-LPPT"}},{"flight":{"flightno":"BA0489","timestamp":"2011-03-20 09:40:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0475","timestamp":"2011-03-19 16:51:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW489","timestamp":"2011-03-18 08:08:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"BA0799","timestamp":"2011-03-17 18:37:02","route":"EGLL>EFHK"}},{"flight":{"flightno":"BAW799","timestamp":"2011-03-17 16:31:01","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW794","timestamp":"2011-03-17 11:55:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"GEUUZ","timestamp":"2011-03-17 09:43:02","route":""}},{"flight":{"flightno":"BAW487","timestamp":"2011-03-16 19:32:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW486","timestamp":"2011-03-16 16:57:02","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW459","timestamp":"2011-03-16 14:10:01","route":"LEMD-EGLL"}},{"flight":{"flightno":"BAW41LM","timestamp":"2011-03-16 10:09:02","route":"EGLL-LEMD"}},{"flight":{"flightno":"BA0795","timestamp":"2011-03-16 08:27:02","route":""}},{"flight":{"flightno":"BAW795","timestamp":"2011-03-16 07:01:02","route":"EFHK-EGLL"}},{"flight":{"flightno":"BAW798","timestamp":"2011-03-15 18:23:02","route":"EGLL-EFHK"}},{"flight":{"flightno":"BAW701","timestamp":"2011-03-15 14:24:01","route":"LOWW-EGLL"}},{"flight":{"flightno":"BAW700","timestamp":"2011-03-15 11:04:01","route":"EGLL-LOWW"}},{"flight":{"flightno":"BAW68BL","timestamp":"2011-03-15 08:14:01","route":"LEBL-EGLL"}},{"flight":{"flightno":"BAW82BL","timestamp":"2011-03-14 18:40:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW849","timestamp":"2011-03-14 08:15:02","route":"EPWA-EGLL"}},{"flight":{"flightno":"BAW40CB","timestamp":"2011-03-13 19:30:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW475","timestamp":"2011-03-13 15:30:02","route":"LEBL-EGLL"}},{"flight":{"flightno":"z.NO-FLIGHTNO","timestamp":"2011-03-13 13:00:03","route":""}},{"flight":{"flightno":"BAW474","timestamp":"2011-03-13 12:00:03","route":"EGLL-LEBL"}},{"flight":{"flightno":"BAW4WP","timestamp":"2011-03-13 08:45:02","route":"LPPT-EGLL"}}]}
I then try and parse this using JSONKit but can only get as far down as "flights" I cannot seem to access the "flight" object.
When I do the following
-(void)parseJSON:(NSString *)jsonData{
NSDictionary *deserializedData = [jsonData objectFromJSONString];
for (id key in deserializedData) {
NSLog(#"key: %#, value: %#", key, [deserializedData objectForKey:key]);
}
}
Only the following is put out to the log....
key: flights, value: (
{
flight = {
flightno = BAW906N;
route = "EGLL-EDDF";
timestamp = "2011-03-24 08:38:02";
};
},
{
flight = {
flightno = BAW365;
route = "LFLL-EGLL";
timestamp = "2011-03-24 06:17:01";
};
},
{
flight = {
etc....
I want to be able to get down to each flight and at the moment am stuck!
Get an array of all flights like this:
NSArray *flights = [deserializedData valueForKeyPath:#"flights.flight"];
thats because you have an array of dictionairies in your dictionairy object, acces them like this:
for (NSDictionairy *flight in [deserializedData objectForKey:#"flights"]){
NSLog(#"flight object with route.: %#", [flight objectForKey:#"route"]);
}

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...