zoukankan      html  css  js  c++  java
  • Convert an object into Json using SBJson or other JSON library

    Using SBJson, to convert a object to JSON string, you have to override the proxyForJson method. Like the following,

    The .h file,

    @interface MyCustomObject : NSObject {
       
    NSString *receiverFirstName;
       
    NSString *receiverMiddleInitial;
       
    NSString *receiverLastName;
       
    NSString *receiverLastName2;
    }
    @property (nonatomic, retain) NSString *receiverFirstName;
    @property (nonatomic, retain) NSString *receiverMiddleInitial;
    @property (nonatomic, retain) NSString *receiverLastName;
    @property (nonatomic, retain) NSString *receiverLastName2;

    - (id) proxyForJson;
    - (int) parseResponse :(NSDictionary *) receivedObjects;
    }

    In the implementation file,

        - (id) proxyForJson {

           
    return [NSDictionary dictionaryWithObjectsAndKeys:
                receiverFirstName
    , @"ReceiverFirstName",
                receiverMiddleInitial
    , @"ReceiverMiddleInitial",
                receiverLastName
    , @"ReceiverLastName",
                receiverLastName2
    , @"ReceiverLastName2",
                nil
    ];
       
    }

    And to get the object from the JSON string you have to write a parseResponse method like this,

    - (int) parseResponse :(NSDictionary *) receivedObjects {
        self
    .receiverFirstName = (NSString *) [receivedObjects objectForKey:@"ReceiverFirstName"];
        self
    .receiverLastName = (NSString *) [receivedObjects objectForKey:@"ReceiverLastName"];

       
    /* middleInitial and lastname2 are not required field. So server may return null value which
         eventually JSON parser return NSNull. Which is unrecognizable by most of the UI and functions.
         So, convert it to empty string. */

       
    NSString *middleName = (NSString *) [receivedObjects objectForKey:@"ReceiverMiddleInitial"];
       
    if ((NSNull *) middleName == [NSNull null]) {
            self
    .receiverMiddleInitial = @"";
       
    } else {
            self
    .receiverMiddleInitial = middleName;
       
    }

       
    NSString *lastName2 = (NSString *) [receivedObjects objectForKey:@"ReceiverLastName2"];
       
    if ((NSNull *) lastName2 == [NSNull null]) {
            self
    .receiverLastName2 = @"";
       
    } else {
            self
    .receiverLastName2 = lastName2;
       
    }

       
    return 0;
    }
  • 相关阅读:
    Linux常用命令(二)
    C#异步调用
    Ajax运用总结
    SQL Server2005 FOR XML PATH 语句的应用
    SQL Server 2005 处理交叉表
    如何控制并发和控制死锁(内含pb的处理要点)
    WPF 中的换行符
    C#委托的异步调用
    pivot 附近有语法错误,您可能需要将当前数据库的兼容级别设置为更高的值。
    应用系统BUG分布小结
  • 原文地址:https://www.cnblogs.com/neozhu/p/2431890.html
Copyright © 2011-2022 走看看