如何在目标C中将类对象转换为JSON字符串 [英] How to convert class object to json string in objective c

查看:168
本文介绍了如何在目标C中将类对象转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1.我创建了类对象,然后使用此代码将值添加到我的类中

1.I create class objects then add value to my class with this code

csJastorPollQuestion *pq = [[csJastorPollQuestion alloc] initWithID:@"01" Name:@"AAA"];

2.我在存在的NSLog中显示了"csJastorPollQuestion"

2.I shown "csJastorPollQuestion" in NSLog it's present

#<csJastorPollQuestion: id = (null) { ID = 01; Name = AAA; }>

3.我使用此代码将"csJastorPollQuestion"转换为json字符串

3.I convert "csJastorPollQuestion" to json string with this code

NSData *jsd = [NSJSONSerialization dataWithJSONObject:pq options:NSJSONWritingPrettyPrinted error:&er];
NSString *jsonString = [[NSString alloc] initWithData:jsd encoding:NSUTF8StringEncoding];

4.运行项目时,显示为错误

4.When I run my project it's shown error this

[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

5.将"csJastorPollQuestion"转换为json字符串的正确方法是什么?

5.What is the right way for convert "csJastorPollQuestion" to json string?

推荐答案

dataWithJSONObject:options:error:方法仅适用于NSJSONSerialization知道如何转换为JSON的对象.这意味着:

The dataWithJSONObject:options:error: method only works on objects that NSJSONSerialization knows how to convert to JSON. That means:

  • 顶级对象必须是NSArrayNSDictionary
  • 包含的对象必须是NSStringNSNumberNSArrayNSDictionaryNSNull的实例.
  • 字典键必须为NSString s
  • 数字不能为无限或NaN.
  • The top-level object must be an NSArray or NSDictionary
  • Objects contained must be instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • Dictionary keys must be NSStrings
  • Numbers must not be infinite or NaN.

您需要转换为字典或数组表示形式才能使用此方法.

You need to convert to a dictionary or array representation to use this method.

这篇关于如何在目标C中将类对象转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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