10. 用json格式保存配置档

2014-04-15  本文已影响77人  Jingwei

原因

原因很简单,比如一个人有很多收货地址,这时候从服务器接收到了地址列表,但服务器的数据格式是json,你想给列表做缓存,所以最直接的想法就是把json address list 保存到地址列表里面

解决

之前我们说过了怎么保存plist,朋友问了,这个没什么难度啊。直接把列表字符串放进去就是了!

但有些许的不同,服务器传过来的数据是

[manager POST:url parameters:parameters success:^( id responseObject) {}

注意是id类型,不是我们所要的字符串,我们怎么把这个类型转成json字符串呢?

强制转换? 可以是可以,你试试吧,不行再往下看。

这里我们利用jsonkit开源库

如:

2014-04-12 11:12:08.201 Incidentally[902:60b] obj: {
    message = "RECEIVEADDRESS_FIND_SUCCESS";
    object =     (
       {
            area = "\"\"";
            city = zabei;
            isdefault = "<null>";
            moblephone = 22222222222;
            province = shanghai;
            receiveaddid = "RECEIVEADDRESS:b8447f44e2434632925e6b2f68389b91";
            receiveaddress = Abcdefasdfjksdhjfk;
            receivename = sdfsdfsdfsdfsdf;
            reluserid = "USERINFO:7c9cf1dcf69f4765bcc45a84a16efbae";
            remarks = "<null>";
            telphone = "<null>";
        }

       {
            area = "\"\"";
            city = zabei;
            isdefault = "<null>";
            moblephone = 1111111111111;
            province = shanghai;
            receiveaddid = "RECEIVEADDRESS:b8447f44e2434632925e6b2f68389b91";
            receiveaddress = Abcdefasdfjksdhjfk;
            receivename = sdfsdfsdfsdfsdf;
            reluserid = "USERINFO:7c9cf1dcf69f4765bcc45a84a16efbae";
            remarks = "<null>";
            telphone = "<null>";
        }

    );
    type = success;
}

先把object读出来,然后利用jsonkit的序列化,再保存到配置档。

NSArray* s = [data objectForKey:@"object"]; // data是整个json对象
[[XXX sharedInstance] setKey:@"address" Value:[s JSONString]]; // xxx是你自己的类

那么相对应的读呢?

- (BOOL) getAddressFromConfig
{
    NSString* address = [[XXX sharedInstance] getKey:@"address"];
    NSArray* array = [address objectFromJSONString];
    if (array != nil)
    {
        for (NSDictionary* receiveaddress in array)
        {
                    // TODO
        }
        [_tableView reloadData];
        return YES;
    }
    return NO;
}

要说的话

这其实是一个错误的解决过程,没啥难度。。。

上一篇下一篇

猜你喜欢

热点阅读