Issue : Convert an Object to json in iOS

▼魔方 西西 提交于 2019-12-18 09:56:15

问题


I have one main entity class with name "Store" like :

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

Here in Store class, i am taking one more class name "Sign In", that include some other attributes.

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

SignIn.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

Now i need to post this Store object on server. So I am creating dictionary using below code :

  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] ;

But i am not getting correct JSON, can you please check my code and let me know where is my mistake. Thanks in Advance.


回答1:


If you are working on iOS 5+, then you can use NSJSONSerialization.

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



回答2:


You should serialize your NSMutableDictionary to JSON. You can do this by using NSJSONSerialization:

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

This should give you your JSON.




回答3:


But i am not getting correct JSON, can you please check my code and let me know where is my mistake.

The problem is that you're not creating a JSON representation of the object anywhere; you're only creating a dictionary. Dictionaries can be converted to JSON (provided that they only contain certain types of data), but they're not JSON natively -- they're Objective-C objects. You probably want to add a call like:

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

You've shown us the NSCoding methods in your two classes, but you should understand that NSJSONSerialization doesn't rely on NSCoding, so none of that code is going to come into play.

Update: After modifying your example to include NSJSONSerialization, you say you're getting JSON that looks like this:

{"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}]}

That appears to be correct, given the values that you've added to dictionnary. But you say that what you want is:

{ "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" }]

That doesn't at all match the object that you're passing to NSJSONSerialization. So, the problem here is that you're supplying incorrect data to NSJSONSerialization.




回答4:


Try with

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];
}


来源:https://stackoverflow.com/questions/20543740/issue-convert-an-object-to-json-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!