如何将如下所示的json字符串转换为字典?

时间:2016-08-22 11:05:05

标签: ios json nsstring nsdictionary

我有一个像这样的json:

`{
   "_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.
}`

但是,我使用我的方法将json字符串带到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解析失败:%@",err);
    return nil;
}
return dic;
}

我失败了,得到一本零字典。

因此,我将data' =转换为:,然后使用+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString将转换后的json字符串转换为字典,我又失败了

是否有一些有用的方法可以将此类json字符串转换为字典?

2 个答案:

答案 0 :(得分:2)

您的json字符串错误,请检查一次,它应该是这样的

{
"_j_msgid" : 2404589949,
"aps" :     {
    "alert" : "E\\U519c\\U901a",
    "badge" : 26,
    "sound" : "happy.caf"
},
"data" : "{title=\\U901a%5CU77e5\\U516c%5CU544a, pushId=15, pushType=NOTICECOL}"}

答案 1 :(得分:0)

我尝试了解决方案而且得到了它。

你的json在上面。这是json的响应。无论你将JSON转换为字符串,它应该是

NSString *strJson = @"{\"_j_msgid\":\"2404589949\",\"aps\" : {\"alert\" :\"EU519cU901a\",\"badge\":\"26\",\"sound\":\"happy.caf\"},\"data\":{\"title\" :\"U901aU77e5U516cU544a\",\"pushId\":\"15\",\"pushType\":\"NOTICECOL\"}}";

当你转换成字符串时,你应该添加

  

\ “键\”:\ “值\”

如果是字典

  

{\ “键\”:\ “值\”}

如果dictioanry在数组内

  

[\ “响应\”:{\ “键\”:\ “值\”}]

然后编码

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);

打印结果

json is - {
 "_j_msgid" = 2404589949;
 aps =     {
    alert = EU519cU901a;
    badge = 26;
    sound = "happy.caf";
 };
 data =     {
    pushId = 15;
    pushType = NOTICECOL;
    title = U901aU77e5U516cU544a;
 };
}