0

我有这个类,FieldValue 和 FieldValues

//
//  FieldValue.h
//

#import <Foundation/Foundation.h>

@interface FieldValue : NSObject
{
    NSString *ident;
    NSMutableArray *values;
    //NSString *values;
}

@property (copy, nonatomic) NSString *ident;
@property (copy, nonatomic) NSMutableArray *values;
//@property (copy, nonatomic) NSString *values;

+ (FieldValue *)fvFromDictionary:(NSDictionary *)dictionary;
+ (FieldValue *)fvInit;
//- (NSDictionary *)dictionaryFromFieldValue:(FieldValue*)fieldValue;

@end
=====================================================================================
//
//  FieldValue.m
//

#import "FieldValue.h"

@implementation FieldValue

@synthesize ident;
@synthesize values;


+ (FieldValue *)fvFromDictionary:(NSDictionary *)dictionary {

    FieldValue *fv = [[FieldValue alloc] init];
    //fv.values = [[NSMutableArray alloc] init];

    fv.ident = [dictionary objectForKey:@"id"];
    fv.values = [dictionary objectForKey:@"values"];

    return fv;
}

+ (FieldValue *)fvInit
{

    FieldValue *fv = [[FieldValue alloc] init];

    fv.ident = @"";
    fv.values = [[NSMutableArray alloc] init];

    return fv;
}

//Inicializa NSMutableArray
- (id) init
{
    if (self = [super init])
    {
        values = [NSMutableArray array];
        //values = [[NSMutableArray alloc] init];
    }
    return self;
}
================================================================
//
//  FieldValues.h
//

#import <Foundation/Foundation.h>

@interface FieldValues : NSObject

@property (strong, nonatomic) NSMutableArray *dataFieldValue;
@end
==================================================================

//
//  FieldValues.m

#import "FieldValues.h"

@implementation FieldValues

@synthesize dataFieldValue;

- (id) init {
    if (self = [super init]){
        dataFieldValue = [NSMutableArray array];
        //dataFieldValue = [[NSMutableArray alloc] init];
    }
    return self;
}

@end
==================================================================

在我的 prefieldsViewController 类中,我有:

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];

    if (self) {
        // Custom initialization

        fvs  = [[FieldValues alloc] init];

        fv = [[FieldValue alloc] init];
        fv0 = [[FieldValue alloc] init];
        fv1 = [[FieldValue alloc] init];
        fv2 = [[FieldValue alloc] init];
        fv3 = [[FieldValue alloc] init];
        fv4 = [[FieldValue alloc] init];
        fv5 = [[FieldValue alloc] init];
        fv6 = [[FieldValue alloc] init];

}
    return self;
}

在我班的其他部分,我有:

======================================================
array= [[NSMutableArray alloc] init];

    if(numButtonFields > 0)
    {
        fv6 = [fvs.dataFieldValue objectAtIndex:numTextFields];
        NSLog(@"Button Value ID[%@]", fv6.ident);
        NSLog(@"Button Values[%@]", [fv6.values objectAtIndex:0]);
        dict = [NSMutableDictionary dictionary];
        [dict setObject:fv6.ident forKey:@"id"];
        [dict setObject:fv6.values forKey:@"value"];
        [array addObject:dict];
    }

    for(int m = 0; m < numTextFields; m++)
    {
        fv = [fvs.dataFieldValue objectAtIndex:m];
        NSLog(@"Field Value ID[%@]", fv.ident);
        NSLog(@"Field Values[%@]", [fv.values objectAtIndex:0]);
        dict = [NSMutableDictionary dictionary];
        [dict setObject:fv.ident forKey:@"id"];
        [dict setObject:fv.values forKey:@"value"];
        [array addObject:dict];
    }
================================================

正确保存到 dict 和数组对象中的值: 现在,我必须将 JSON 格式的 HTTP POST 发送到 Windows Web 服务,我这样做:

================================================
- (void)fetch
{

    contract_id = [contract_id stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    @try
    {
        NSString *absoluteUrl = [NSString stringWithFormat:@"https://www****************************************************.svc/user/payments/services/%@/pre", service_id];

        NSURL *serviceUrl = [NSURL URLWithString:absoluteUrl];

        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];

        NSDictionary *tmp = [NSDictionary dictionaryWithObjectsAndKeys:
                             auth_token, @"auth_token",
                             private_token, @"private_token",
                             array, @"field_values",
                             [NSString stringWithFormat:@"%g", paymentAmount] , @"amount",
                             account1, @"account_id",
                             [creditokenField text], @"confirmation_key",
                             @"false", @"commission",
                             nil];

        NSURLResponse *response;
        NSError* error;

        //***************//
        //Checking null values

        NSLog(@"array[%@]", [array objectAtIndex:0]);
        NSLog(@"array[%@]", [array objectAtIndex:1]);
        NSLog(@"array[%@]", [array objectAtIndex:2]);
        NSLog(@"array[%@]", [array objectAtIndex:3]);

        NSMutableArray *llave = [tmp objectForKey:@"field_values"];
        NSString *cuenta = [tmp objectForKey:@"account_id"];

        NSLog(@"Data[%@]", [llave objectAtIndex:0]);
        NSLog(@"Cuenta[%@]", cuenta);


        //***************//

        //NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
        NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error:nil];
        //NSString* str = [NSString stringWithFormat:@"%.*s", [postdata length], [postdata bytes]];
        NSString* str = [[NSString alloc] initWithData:postdata encoding:NSJSONWritingPrettyPrinted];

        NSLog(@"URL for pre pago service[%@]", absoluteUrl);
        NSLog(@"Post data for pre pago service[%@]", str);
        NSLog(@"Post data for pre pago error[%@]", error);
        NSLog(@"data for pre pago[%@]", postdata);

        str = [NSString stringWithFormat:@"%.*s", [postdata length], [postdata bytes]];
        NSLog(@"Request data from pre pago service[%@]", str);

        [request setHTTPMethod:@"POST"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d", [postdata length]] forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:postdata];


        NSString *requestPOST = [[request URL] absoluteString];
        NSLog(@"Request %@", requestPOST);

       NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

        str = [NSString stringWithFormat:@"%.*s", [responseData length], [responseData bytes]];

        NSLog(@"Response data from pre pago service[%@]", str);
        NSLog(@"Incoming data%@", str);


        SBJsonParser *jsonParser = [SBJsonParser   new];
        NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:str error:nil];

        NSLog(@"%@",jsonData);

        rsp_message  = [jsonData objectForKey:@"message"];
        rsp_code = [jsonData objectForKey:@"success"];

        NSLog(@"Response Code ==> [%@]", rsp_code);
        NSLog(@"Response Message ==> [%@]", rsp_message);


        if(!([rsp_code boolValue] == 0))
        {
            rsp_code = @"0";
            NSLog(@"Response Code[%@]",rsp_code);
            [self performSelectorOnMainThread:@selector(showAlert:) withObject:rsp_code waitUntilDone:NO];
        }
        else
        {
            rsp_code = @"-1";
            NSLog(@"Response Code[%@]",rsp_code);
            [self performSelectorOnMainThread:@selector(showAlert:) withObject:rsp_code waitUntilDone:NO];
        }

        [actividad stopAnimating];
    }
    @catch (NSException * e)
    {
        NSLog(@"Exception in data: %@", e);
        rsp_code = @"-2";
        NSLog(@"Response Code[%@]",rsp_code);
        ///[self alertStatus:@"Error" :@"Transacción inválida!"];
        [self performSelectorOnMainThread:@selector(showAlert:) withObject:rsp_code waitUntilDone:NO];
        ///[self alertStatus:@"No se encuentran registros." :@""];
        [actividad stopAnimating];
    }}
================================================

我发送的结构是:

2013-05-24 14:20:58.600 *************[16197:1a4f] Request data from pre pago service[{
  "private_token" : "62ee7b86-71db-4648-87d4-10259c705acd",
  "confirmation_key" : "123456",
  "amount" : "123",
  "commission" : "false",
  "account_id" : "201-50530825-2-19",
  "auth_token" : "29118768-f24c-497b-a233-2daee10bec96",
  "field_values" : [
    {
      "id" : "1",
      "value" : [
        "Telefono"
      ]
    },
    {
      "id" : "2",
      "value" : [
        "11"
      ]
    },
    {
      "id" : "3",
      "value" : [
        "22"
      ]
    },
    {
      "id" : "4",
      "value" : [
        "33"
      ]
    }
  ]
}]

该结构正确传输到 de Windows 服务,但此服务在 field_values 的值嵌套数组中接收空值:

"private_token" : "62ee7b86-71db-4648-87d4-10259c705acd",
  "confirmation_key" : "123456",
  "amount" : "123",
  "commission" : "false",
  "account_id" : "201-50530825-2-19",
  "auth_token" : "29118768-f24c-497b-a233-2daee10bec96",
  "field_values" : [
    {
      "id" : "1",
      "value" :
          null
    },
    {
      "id" : "2",
      "value" :
          null
    },
    {
      "id" : "3",
      "value" :
          null
    },
    {
      "id" : "4",
      "value" :
          null
    }
  ]
}]

有人可以帮助我吗?

4

1 回答 1

0

根据我的观察,您发送的值不是正确的 JSON 可接受格式。

您的问题示例:

{
      "id" : "1",
      "value" : [ // Not a proper structure
        "Telefono"
      ]
}

JSON [] 中的方括号表示一个数组。由于您没有发送数组,因此可能会发生这种情况。

尝试如下格式:

{
      "id" : "1",
      "value" : "Telefono"
}

以上应该工作。因为这里不需要数组。

但是,如果您需要发送一组值,您可以按照以下方式进行操作,

{
      "id" : "1",
      "values" : [ {
        "value" : "Telefono"// You can add any number of key value pairs here
       },{ 
         "value" : "Foo"
        },{
          "value" : "Bar"
        }
      ]
    }
于 2013-05-27T04:51:23.753 回答