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;
    }
  • 相关阅读:
    【嵌入式】arm-linux-gcc/ld/objcopy/objdump参数概述
    【Java】Java复习笔记-第四部分
    【C/C++】C语言复习笔记-17种小算法-解决实际问题
    【Java】Java复习笔记-三大排序算法,堆栈队列,生成无重复的随机数列
    【Java】Java复习笔记-第三部分
    【教程】ubuntu下安装NFS服务器
    【Java】Java复习笔记-第二部分
    【Java】Java复习笔记-第一部分
    【教程】ubuntu下安装samba服务器
    【C/C++】一道试题,深入理解数组和指针
  • 原文地址:https://www.cnblogs.com/neozhu/p/2431890.html
Copyright © 2011-2022 走看看