解析json NSlog xcode

时间:2015-07-01 15:37:47

标签: ios objective-c json

我已经获得了这个JSON数据,我想将它解析为3个类别:“guid”,“exponent”和“modulus”。我该怎么办?感谢您的帮助!

  

2015-07-01 11:02:51.972 Acculunk KeyPad [4717:1667358]回复正文:   { “ERROR_CODE”:0, “ERROR_MESSAGE”: “”, “指数”: “010001”, “GUID”: “855fd04f-0016-1805-a3be-84dbef17ffd6”, “弹性模量”: “C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5”, “tran_id”: “cb2e8149-4961-458a-a6b2-7443bdb01509”}
  2015-07-01 11:03:37.175 Acculunk KeyPad [4717:1674710]终止,因为没有系统应用程序。

以下是代码:

NSString *temp2 = [NSString stringWithFormat:@"{\n  \"partner_key\": \"%@\",\n  \"auth_token\": \"QaU9QcFZ6xE7aiRRBge0wZ4p6E01GEbl\",\n  \"payment_account_id\": \"%@\",\n  \"card_number\": \"%@\",\n  \"card_exp_date\": \"%@\",\n  \"amount\": \"%@\",\n  \"memo\": \"%@\",\n  \"recipient\": {\n    \"email\": \"%@\",\n    \"mobile_phone\": \"%@\"\n  }\n}",[Partner_Key text], [Payment_Account_ID text], [Card_Number text], [Card_Exp_Date text], [Amount text],[Memo text], [Recipient_Email text], [Recipient_Phone_Number text]];
NSLog(temp2);

NSURL *URL = [NSURL URLWithString:@"https://cert.payzur.com/payzurservices.svc/payment/send/initiate"];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:@"POST"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:[temp2 dataUsingEncoding:NSUTF8StringEncoding]];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                        completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {

                                  if (error) {
                                      // Handle error...
                                      return;
                                  }

                                  if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
                                      NSLog(@"Response HTTP Status code: %ld\n", (long)[(NSHTTPURLResponse *)response statusCode]);
                                      NSLog(@"Response HTTP Headers:\n%@\n", [(NSHTTPURLResponse *)response allHeaderFields]);
                                  }

                                  NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                  NSLog(@"Response Body:\n%@\n", body);

                                  NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
                                  NSError *e;
                                  NSDictionary *res = [NSJSONSerialization JSONObjectWithData:body options:nil error:&e];
                                  if (res) {
                                      NSNumber *errorCode    = res[@"error_code"];

                                      NSString *errorMessage = res[@"error_message"];

                                      NSString *guid         = res[@"guid"];

                                      NSString *exponent     = res[@"exponent"];

                                      NSString *modulus      = res[@"modulus"];

                                  }
                                  else {
                                      NSLog(@"Error: %@", error);
                                  }




                              }];
[task resume];

4 个答案:

答案 0 :(得分:2)

假设此数据为NSData类型,您可以执行以下操作:

NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&myError];

NSNumber *errorCode = res[@"error_code"];
NSString *errorMessage = res[@"error_message"];
NSString *guid = res[@"guid"];
NSString *exponent = res[@"exponent"]; // Maybe also a NSNumber?
NSString *modulus = res[@"modulus"];

数据将在五个变量中提供:

  • 的errorCode
  • 的errorMessage
  • GUID
  • 指数
  • 模量

答案 1 :(得分:1)

使用+ JSONObjectWithData:options:error:创建NSDictionary JSON。

然后以通常的方式访问字典项目来访问元素。

ChristopherMäuer使用字面语法答案:

NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:apiReturn options:0 error:&error];
if (res) {
    NSNumber *errorCode    = res[@"error_code"];
    NSString *errorMessage = res[@"error_message"];
    NSString *guid         = res[@"guid"];
    NSString *exponent     = res[@"exponent"]; // Maybe also a NSNumber?
    NSString *modulus      = res[@"modulus"];
}
else {
    NSLog(@"Error: %@", error);
}

更新了新的问题代码:

以下是示例代码,我已经重新构建了从注销中收到的数据:

NSString *responseBody = @"{\"error_code\":0,\"error_message\":\"\",\"exponent\":\"010001\",\"guid\":\"855fd04f-0016-1805-a3be-84dbef17ffd6\",\"modulus\":\"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5\",\"tran_id\":\"cb2e8149-4961-458a-a6b2-7443bdb01509\"}";
NSData *data = [responseBody dataUsingEncoding:NSUTF8StringEncoding];
// The above was just to get `data` setup.

// The only function of the following two statements is to print the data as a string.
NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response Body:\n%@\n", body);
//
// NSData *jsonData = [body dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(@"res: \n%@", res);

if (res) {
    NSNumber *errorCode    = res[@"error_code"];
    NSString *errorMessage = res[@"error_message"];
    NSString *guid         = res[@"guid"];
    NSString *exponent     = res[@"exponent"];
    NSString *modulus      = res[@"modulus"];
    NSLog(@"errorCode: %@\nerrorMessage: %@\nguid: %@\nexponent: %@\nmodulus: %@", errorCode, errorMessage, guid, exponent, modulus);
}
else {
    NSLog(@"Error: %@", error);
}

输出:

Response Body:
{"error_code":0,"error_message":"","exponent":"010001","guid":"855fd04f-0016-1805-a3be-84dbef17ffd6","modulus":"C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5","tran_id":"cb2e8149-4961-458a-a6b2-7443bdb01509"}

res: 
{
    "error_code" = 0;
    "error_message" = "";
    exponent = 010001;
    guid = "855fd04f-0016-1805-a3be-84dbef17ffd6";
    modulus = C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5;
    "tran_id" = "cb2e8149-4961-458a-a6b2-7443bdb01509";
}

errorCode: 0
errorMessage: 
guid: 855fd04f-0016-1805-a3be-84dbef17ffd6
exponent: 010001
modulus: C44274FBD65D79B7F9ADF5255A563A5B8B8438D30F8E2CAD16950BE8675827B94F4F8040D4A9563811F405F8E94A20A69DCC0CA590F8731803AB4682497C0DC2520AD2AEB2CC4ED159276335C83B4FB4CB44966448081C625DF88D019118B7448684743EFB6D6704F8F8BD79875ACAEFC541DA3661D0D00BDDF115382A64C5C5

答案 2 :(得分:0)

我建议你更换以下两行:

// Header
var p = p2.Range.Paragraphs.Add();
var x = p.Range.Paragraphs.Count;
p.Range.Text = String.Format(headerText + "\r\n");
p.Range.set_Style("Req Level " + layerNumber.ToString() + " - Body");

// Description
p2 = p.Range.Paragraphs.Add();
p2.Range.Text = String.Format(bodyText + "\r\n");
p2.Range.set_Style("Req Level " + layerNumber.ToString());

使用我提供的两个代码行:

NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response Body:\n%@\n", body);

或以下内容:

     NSError *error;
     NSDictionary* responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

所以现在你有 NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data]; NSDictionary,所以现在我们可以按如下方式解码你的JSON响应(我将整个代码如下):

responseData

因此,您在问题中粘贴的所有代码如下所示:

     NSString* body = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
     NSDictionary *responseData = [[NSDictionary alloc] initWithDictionary:(NSDictionary *)data];

     NSString *guid = [responseData valueForKey:@"guid"];

     NSString *exponent = [responseData valueForKey:@"exponent"];

     NSString *modulus = [responseData valueForKey:@"modulus"];


     NSLog(@"Decoded Response :\n guide : %@,\n exponent : %@,\n modulus : %@", guid, exponent, modulus);

答案 3 :(得分:-1)

好吧,你没有说明你如何获得数据,比如你已经在NSString中或者仍然在NSData中,所以我将假设你在NSData中拥有它。

NSData *json <- somehow I magically got jSON data into this
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:json options:kNilOptions error:&error];

NSString guid = [NSString stringWithString:jsonDict[@"guid"];
NSString exponent = [NSString stringWithString:jsonDict[@"exponent"];
NSString modulus = [NSString stringWithString:jsonDict[@"modulus"];