Objective-C / iOS:将对象数组转换为JSON字符串 [英] Objective-C / iOS: Converting an array of objects to JSON string

查看:540
本文介绍了Objective-C / iOS:将对象数组转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用JSON进行互联网数据传输。我已成功接收JSON字符串并将其转换为 NSDictionary ,但无法解决如何将对象的数组或字典转换为JSON表示。

I am currently experimenting with the use of JSON for internet data transfer. I have been successful in receiving a JSON string and converting it into an NSDictionary, but have not been able to work out how to convert an array or dictionary of objects into a JSON representation.

我已阅读了一些帖子和文章,解释了如何创建 NSDictionary 的键/值对然后转换为JSON,它适用于一个简单的数组,但是当你有一个数组或对象字典时,你如何实现这一点。

I have read a number of posts and articles which explain how to create a NSDictionary of key/value pairs and then convert to JSON, which works fine for a simple array, but how do you achieve this when you have an array or dictionary of objects.

所以,例如,我有一个对象数组contact,然后我想将其转换为JSON字符串:

So for example, I have an array of objects "contact", which I would then like to transform into a JSON string as such:

"contacts":{
    "contact":[
    {
        "id":"1"
        "first_name":"john",
        "last_name":"citizen",
        "phone":"9999 9999"
    }
    {
        "id":"1"
        "first_name":"jane",
        "last_name":"doe",
        "phone":"8888 8888"
    }
    ]
 }

我有一个 NSMutableDictionary ,它填写了一个列表联系对象:

I have a NSMutableDictionary which is populate a list of contact objects:

    NSMutableDictionary* contactsToBeSynced = [[NSMutableDictionary alloc] init];
    //Populate dictionary with contact objects.
    contactsToBeSynced = self.getNonSynchronisedData;

然后我尝试使用 NSJSONSerialization 方法,但失败并出现错误。

I then attempt to transform the dictionary of objects with the NSJSONSerialization method, but it fails with an error.

    NSError* error;
    NSString* jsonString;
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:contactsToBeSynced options:NSJSONWritingPrettyPrinted error:&error];
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

有没有人能够成功做到这一点?非常感谢一些帮助或正确方向的一点。干杯。

Has anyone been able to successfully do this? Would greatly appreciate some help or a point in the right direction. Cheers.

推荐答案

关于你的结构 - 你的 contactsToBeSynced 必须是 NSDictionary 类,联系应该是 NSArray 包含 NSDictionary 不同联系人的对象。顺便问一下,你试过 JSONKit 吗?它的序列化比标准 NSJSONSerialization 更好。

About your structure - your contactsToBeSynced must be of NSDictionary class, and contact should be an NSArray containing NSDictionary objects for different contacts. By the way, have you tried JSONKit? It's serialization works better than standard NSJSONSerialization.

这篇关于Objective-C / iOS:将对象数组转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆