有没有办法修复json响应

时间:2014-11-11 05:06:15

标签: ios json parsing swift

我正在解析一个有问题的json。我在Swift中这样做:

jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

所以,它给出了一个错误。

Error converting string to object => Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Badly formed object around character 11396.) UserInfo=0x14512990 {NSDebugDescription=Badly formed object around character 11396.})

现在,响应很大,所以我只发布错误部分:

{
  "data" : {
    "operator_settings" : {
      "profileSettings" : "{"visible":["firstname","lastname","phonenumber","emailaddress","paddress","paddress2","paddresscity","paddressstateabbreviation","paddresszip","paddresscountry"],"required":["firstname","lastname","emailaddress","paddress","paddresscity","paddresszip"]}"
    }
  },
  "status" : 200.0,
  "count" : null
}

另外,我想在解析它之前做出这样的响应:

{
"data": {
    "operator_settings": {
        "profileSettings": "{\"visible\":[\"firstname\",\"lastname\",\"phonenumber\",\"emailaddress\",\"paddress\",\"paddress2\",\"paddresscity\",\"paddressstateabbreviation\",\"paddresszip\",\"paddresscountry\"],\"required\":[\"firstname\",\"lastname\",\"emailaddress\",\"paddress\",\"paddresscity\",\"paddresszip\"]}"
    }
},
"status": 200,
"count": null

}

但是,我不知道答复的深度。我无法访问我正在调用的API。那么,我能做到的解决方案吗?

1 个答案:

答案 0 :(得分:0)

我的要求和你的要求一样。我需要以格式

传递数组值
 "{\n  \"UserId\" : \"1\",\n  \"CorporateId\" : \"1\",\n  \"DataAccessLevel\" : \"1\"\n}"

因此,我创建了以下两种方法:

+ (NSString *) getJSONString:(id)object {

    NSString *jsonString = @"";
    @try {
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        if (! jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {
            jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        return jsonString;
    }
    @catch (NSException *exception) {
        NSLog(@" Exception :%@",exception);
        return jsonString;
    }
}

//---------------------------------------------------------------

+ (id) getObjectFromJSONString:(NSString *)jsonString {
    @try {
        NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        id object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
        return object;
    }
    @catch (NSException *exception) {
        NSLog(@" Exception :%@",exception);
        return nil;
    }
}

此处profileSettings将此对象传递给getJSONString方法,您将获得该格式。