Converting NSString to NSDictionary / JSON

前端 未结 5 1584
时光说笑
时光说笑 2020-12-02 07:05

I have the following data saved as an NSString :

 {
    Key = ID;
    Value =         {
        Content = 268;
        Type = Text;
    };
},
          


        
相关标签:
5条回答
  • 2020-12-02 07:27

    I believe you are misinterpreting the JSON format for key values. You should store your string as

    NSString *jsonString = @"{\"ID\":{\"Content\":268,\"type\":\"text\"},\"ContractTemplateID\":{\"Content\":65,\"type\":\"text\"}}";
    NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    

    Now if you do following NSLog statement

    NSLog(@"%@",[json objectForKey:@"ID"]);
    

    Result would be another NSDictionary.

    {
        Content = 268;
        type = text;
    }
    

    Hope this helps to get clear understanding.

    0 讨论(0)
  • 2020-12-02 07:27

    I think you get the array from response so you have to assign response to array.

    NSError *err = nil;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
    NSDictionary *dictionary = [array objectAtIndex:0];
    NSString *test = [dictionary objectForKey:@"ID"];
    NSLog(@"Test is %@",test);
    0 讨论(0)
  • 2020-12-02 07:27

    Use the following code to get the response object from the AFHTTPSessionManager failure block; then you can convert the generic type into the required data type:

    id responseObject = [NSJSONSerialization JSONObjectWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] options:0 error:nil];
    
    0 讨论(0)
  • 2020-12-02 07:29

    Use this code where str is your JSON string:

    NSError *err = nil;
    NSArray *arr = 
     [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] 
                                     options:NSJSONReadingMutableContainers 
                                       error:&err];
    // access the dictionaries
    NSMutableDictionary *dict = arr[0];
    for (NSMutableDictionary *dictionary in arr) {
      // do something using dictionary
    }
    
    0 讨论(0)
  • 2020-12-02 07:40

    Swift 3:

    if let jsonString = styleDictionary as? String {
        let objectData = jsonString.data(using: String.Encoding.utf8)
        do {
            let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
            print(String(describing: json)) 
    
        } catch {
            // Handle error
            print(error)
        }
    }
    
    0 讨论(0)
提交回复
热议问题