ios - 使用 RestKit 为我的对象获取 JSON 字符串

标签 ios json restkit restkit-0.20

我想创建一个 json 字符串以保存在 NSUserDefaults 中,然后从中取回它。

我已经将 RestKit 添加到我的项目中,用于从服务器发送和接收对象。 但是,现在我想展平并保存数据。

我如何使用 restkit 获取对象的 JSON 字符串?

最佳答案

我需要相同的功能(在我的例子中是将 JSON 作为多部分属性发送),所以经过一段时间的搜索,我得到了解决方案。

您可以使用带有该代码的 RestKit 获取 JSON 数据(和 JSON 字符串),您必须传递要转换的对象以及要用于转换的映射。

RKRequestDescriptor *descriptorObject = ...
Custom *object = ...

NSDictionary *parametersForObject = [RKObjectParameterization parametersWithObject:object requestDescriptor:descriptorObject error:nil];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parametersForObject
                    options:NSJSONWritingPrettyPrinted //Pass 0 if you don't care about the readability of the generated string
                    error:&error];

NSString *jsonString;
if (! jsonData) {
    NSLog(@"Got an error: %@", error);
}
else {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

我没有找到这个文档,我只是浏览代码发现它,我不确定它是公共(public) API 还是私有(private) API。至少,它适用于 RestKit 0.20

关于ios - 使用 RestKit 为我的对象获取 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21522018/

相关文章:

iphone - 搜索不起作用

ios - Swift UICollectionViewCell didSelectItemAt 不在单元格上打印标签名称

javascript - 将 JSON 对象发布到 Web 方法 - $.ajax

c# - 为什么当 DataMember 的名称为 "length"时,我的整个对象都序列化为 Array

ios - 无效的 CfStringRef plist(字典数组)iOS

ios - 像 GrabCut 这样的图像分割算法可以在 iPhone GPU 上运行吗?

java - 如何使用 ArrayAdapter (Java) 将数据插入 MySQL 服务器?

ios - 归档时所有 RestKit 项目都无法构建

ios - Restkit 发布不发送对象

iphone - RestKit - RKObjectMapping 只运行一次