不正确地将json解析为NSDictionary [英] Incorrectly parse json into NSDictionary

查看:166
本文介绍了不正确地将json解析为NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将文本字段数据从json存储到NSDictionary中.我已经为此使用SBJson.

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.

 {  
   "fields":[  
      {  
        "textFields":[  
            {  
              "text":"Congratulations",
              "textSize":"12"
            },
            {  
               "text":"Best Wishes",
               "textSize":"15"
             },
            {  
              "text":"Test  text",
              "textSize":"10"
            }
          ]
       },
      {  
         "imageFields":[  
            {  
               "image":"test1.jpg",
               "width":"200",
           "height":"100"
        },
        {  
           "image":"test2.jpg",
           "width":"200",
           "height":"100"
            }
         ]
       }
    ]
  }

我的代码:

 -(void)readJson{

     NSDictionary *jsonDict = [jsonString JSONValue];
     NSDictionary *fieldsDict =[jsonDict valueForKey:@"fields"];
     NSDictionary *textFieldsDict = [fieldsDict valueForKey:@"textFields"];
     NSLog(@" Dictionary %@ ",textFieldsDict );

}

但是其输出如下.

Dictionary (
     (
             {
         text = Congratulations;
         textSize = 12;
     },
             {
        text = "Best Wishes";
        textSize = 15;
    },
            {
         text = "Test  text";
         textSize = 10;
     }
 ),
 "<null>"
) 

似乎字典中有两项,而一项为空.我想将三个文本字段项放入数组中.我该怎么解决.

It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.

推荐答案

I have corrected the json format and used NSJSONSerialization, 

  {"fields":
   {"textFields":
    [  {"text":"Congratulations", "textSize":"12"},
       {"text":"Best Wishes", "textSize":"15"},
       {"text":"Test  text", "textSize":"10"}
    ],
  "imageFields":
   [  {"image":"test1.jpg","width":"200", "height":"100"},
      {"image":"test2.jpg", "width":"200", "height":"100"}
   ]
 }
}


 -(void)readJson
    NSError *e = nil;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
    NSDictionary *fields = [jsonDict objectForKey:@"fields"];
    NSArray *textArray=[fields objectForKey:@"textFields"] ;
    NSLog(@"--- %@",textArray );
 }

这篇关于不正确地将json解析为NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆