I got a json like this:
`{
"_j_msgid" = 2404589949;
aps = {
alert = "E\U519c\U901a";
badge = 26;
sound = "happy.caf";
};
data = "{title=\U901a\U77e5\U516c\U544a, pushId=15, pushType=NOTICECOL}"; // this line is my want.
}`
But, I use my method to take the json string to dictionary
:
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
if (jsonString == nil) {
return nil;
}
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *err;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&err];
if(err) {
NSLog(@"json fail:%@",err);
return nil;
}
return dic;
}
I failed, get a nil dictionary.
So, I convert the data
's =
to :
,then use + (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
to transform the converted json
string to dictionary, and I failed again.
Is there some useful method to transform this type json
string to dictionary?
I tried the solution and I got it.
Your json is above.That is the json response.Whatever when you convert JSON to string it should be
NSString *strJson = @"{\"_j_msgid\":\"2404589949\",\"aps\" : {\"alert\" :\"EU519cU901a\",\"badge\":\"26\",\"sound\":\"happy.caf\"},\"data\":{\"title\" :\"U901aU77e5U516cU544a\",\"pushId\":\"15\",\"pushType\":\"NOTICECOL\"}}";
When you convert into string you should add
\"key\":\"value\"
If it is dictionary
{\"key\":\"value\"}
If dictioanry is inside the array
[\"response\":{\"key\":\"value\"}]
Then the coding
NSError *jsonError;
NSString *strJson = @"{\"_j_msgid\":\"2404589949\",\"aps\" : {\"alert\" :\"EU519cU901a\",\"badge\":\"26\",\"sound\":\"happy.caf\"},\"data\":{\"title\" :\"U901aU77e5U516cU544a\",\"pushId\":\"15\",\"pushType\":\"NOTICECOL\"}}";
NSData *objectData = [strJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(@"json is - %@",json);
The printed results are
json is - {
"_j_msgid" = 2404589949;
aps = {
alert = EU519cU901a;
badge = 26;
sound = "happy.caf";
};
data = {
pushId = 15;
pushType = NOTICECOL;
title = U901aU77e5U516cU544a;
};
}