【问题标题】:Issue : Convert an Object to json in iOS问题:在 iOS 中将对象转换为 json
【发布时间】:2013-12-12 12:35:04
【问题描述】:

我有一个名为“Store”的主要实体类,例如:

Store.h :-

#import <Foundation/Foundation.h>
#import "SignIn.h"

@interface Store : NSObject

@property (nonatomic, retain) NSString *storeId;
@property (nonatomic, retain) NSString *storeProfileId;
@property (nonatomic, retain) NSString *storeName;
@property (nonatomic, retain) NSString *storeRegion;

@property (nonatomic, retain) SignIn *signIn;

@end

Store.m :-

#import "Store.h"

@implementation Store

@synthesize storeId, storeProfileId, storeName, storeRegion, signIn;

- (id) initWithCoder: (NSCoder *)coder
{
    self = [[Store alloc] init];
    if (self != nil)
    {
        self.storeId = [coder decodeObjectForKey:@"storeId"];
        self.storeProfileId = [coder decodeObjectForKey:@"storeProfileId"];
        self.storeName = [coder decodeObjectForKey:@"storeName"];
        self.storeRegion = [coder decodeObjectForKey:@"storeRegion"];

        self.signIn = [coder decodeObjectForKey:@"signIn"];
    }
    return self;
}

- (void)encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject:storeId forKey:@"storeId"];
    [coder encodeObject:storeProfileId forKey:@"storeProfileId"];
    [coder encodeObject:storeName forKey:@"storeName"];
    [coder encodeObject:storeRegion forKey:@"storeRegion"];

    [coder encodeObject:signIn forKey:@"signIn"];
}

@end

在 Store 类中,我又取了一个类名“登录”,其中包括一些其他属性。

SignIn.h :-

#import <Foundation/Foundation.h>

@interface SignIn : NSObject

@property (nonatomic, retain) NSString *inTime;
@property (nonatomic, retain) NSString *outTime;
@property (nonatomic, retain) NSString *isStatus;

@end

登录.m :-

#import "SignIn.h"

@implementation SignIn
@synthesize inTime, outTime, isStatus;

- (id) initWithCoder: (NSCoder *)coder
{
    self = [[SignIn alloc] init];
    if (self != nil)
    {
        self.inTime = [coder decodeObjectForKey:@"inTime"];
        self.outTime = [coder decodeObjectForKey:@"outTime"];
        self.isStatus = [coder decodeObjectForKey:@"isStatus"];
    }
    return self;
}

- (void)encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject:inTime forKey:@"inTime"];
    [coder encodeObject:outTime forKey:@"outTime"];
    [coder encodeObject:isStatus forKey:@"isStatus"];
}

@end

现在我需要在服务器上发布这个 Store 对象。所以我正在使用下面的代码创建字典:

  NSMutableArray *storeJSONArray=[NSMutableArray array];
    for (Store *store in array1) {

        NSMutableDictionary *storeJSON=[NSMutableDictionary dictionary];

        [storeJSON setValue:store.storeId forKey:@"storeId"];
        [storeJSON setValue:store.storeProfileId forKey:@"storeProfileId"];
        [storeJSON setValue:store.storeName forKey:@"storeName"];
        [storeJSON setValue:store.storeRegion forKey:@"storeRegion"];


        //Sign In
        [storeJSON setValue:store.signIn.inTime forKey:@"inTime"];
        [storeJSON setValue:store.signIn.outTime forKey:@"outTime"];
        [storeJSON setValue:store.signIn.isStatus forKey:@"isStatus"];

        [storeJSONArray addObject:storeJSON];
    }

    NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
    [dictionnary setObject:storeJSONArray forKey:@"StoreRequest"];

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
                                                       options:kNilOptions
                                                         error:&error];

    NSString *urlString =@"http://...................php";

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:jsonData];
    NSURLResponse *response = NULL;
    NSError *requestError = NULL;

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

    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] ;

但是我没有得到正确的 JSON,请你检查我的代码,让我知道我的错误在哪里。提前致谢。

【问题讨论】:

  • 不清楚你在问什么。
  • @Virussmcahere 是我的一个名为“Store”的实体类,只有我需要将该类对象转换为 JSON。但我不知道我在哪里弄错了。
  • 不,实际上它并没有在任何地方崩溃,但它不是以 JSON 格式出现的,而且价值也没有出现。
  • 你应该使用NSJSONSerialization
  • 我的 JSON 在一个范围内。但它应该包含多个范围。

标签: ios objective-c json nsmutabledictionary


【解决方案1】:

如果您使用的是 iOS 5+,那么您可以使用NSJSONSerialization

NSData *data= [NSJSONSerialization dataWithJSONObject:storeJSONArray 
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:nil];
if (data)
{
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"JSON : %@",json );
}

【讨论】:

  • @MidhunThanks..是的,我正在使用 iOS 5+。请检查我更新的问题。我正在使用 php url 在服务器上发布一个对象。
  • @MidhunMP 在 JSON 中只显示一个范围。
  • @AnandGautam:您确定您的 storeJSONArray 包含所有对象吗?我认为它只有一个对象。
  • @MidhuniYes 这个 storeJSONArray 只是一个 Store 对象的数组。但是商店还有一个名为“登录”的实体类
  • @AnandGautam:那又怎样?您将这些值添加到 NSDictionary 并将其添加到数组中。所以价值在同一水平。否则转换您的 array1 并检查
【解决方案2】:

您应该将您的 NSMutableDictionary 序列化为 JSON。 您可以使用 NSJSONSerialization 来做到这一点:

NSError *error;
NSData *myData = [NSJSONSerialization dataWithJSONObject:storeJSON options:0 error:&error];
NSString *myJSON = [[NSString alloc] initWithBytes:[myData bytes]];

这应该会给你你的 JSON。

【讨论】:

    【解决方案3】:

    但是我没有得到正确的 JSON,请你检查我的代码,让我知道我的错误在哪里。

    问题是您没有在任何地方创建对象的 JSON 表示;你只是在创建一个字典。字典可以转换为 JSON(前提是它们只包含某些类型的数据),但它们本身不是 JSON——它们是 Objective-C 对象。您可能想要添加如下调用:

    NSError *error = nil;
    NSData *json = [NSJSONSerialization dataWithJSONObject:dictionnary options:0 error:&error];
    

    您已经向我们展示了您的两个类中的 NSCoding 方法,但您应该了解 NSJSONSerialization 不依赖 NSCoding,因此这些代码都不会发挥作用。

    更新:在修改示例以包含 NSJSONSerialization 后,您说您得到的 JSON 如下所示:

    {"StoreRequest":[{"signOutStatus":false,"greetingStatus":false,"isBackFromVisit"‌​‌​:false,"digitalMerchandisingStatus":false,"feedbackStatus":false,"storeRegion":‌​"B‌​ishan Junction 8","isSubmit":false,"storeName":"Best Denki","storeId":"SG-2","planVisitStatus":false,"storeProfileId":5,"merchandisin‌​‌​gStatus":false}]}
    

    鉴于您添加到dictionnary 的值,这似乎是正确的。但是你说你想要的是:

    { "Checklist": [ { "vm_code": "SGVM0001", "store_id": "SG-12", "store_name": "Best Denki", "store_address": "Ngee Ann City", "visit_date": { "date": "2013-12-04 00:00:00", "timezone_type": 3, "timezone": "Asia/Calcutta" } "sign_in": { "date": "2013-12-05 11:03:00", "timezone_type": 3, "timezone": "Asia/Calcutta" }]
    

    这与您传递给 NSJSONSerialization 的对象完全不匹配。所以,这里的问题是你向 NSJSONSerialization 提供了不正确的数据。

    【讨论】:

    • @CalebThanksActually NSCoding,我已经开始在他们的字段中显示价值。我正在使用 NSJSONSerialization 但它仍然没有显示。
    【解决方案4】:

    试试

    NSError *error; 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput 
                                                       options:kNilOptions // Pass 0 if you don't care about the readability of the generated string
                                                         error:&error];
    
    if (! jsonData) {
        NSLog(@"Got an error: %@", error);
    } else {
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-21
      • 2020-10-28
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      相关资源
      最近更新 更多