我创建了一个struct并希望将其保存为JSON文件.
struct Sentence {
var sentence = ""
var lang = ""
}
var s = Sentence()
s.sentence = "Hello world"
s.lang = "en"
print(s)
Run Code Online (Sandbox Code Playgroud)
...导致:
Sentence(sentence: "Hello world", lang: "en")
Run Code Online (Sandbox Code Playgroud)
但是我怎样才能将struct对象转换为:
{
"sentence": "Hello world",
"lang": "en"
}
Run Code Online (Sandbox Code Playgroud) 在过去的10个小时里一直试图调试崩溃,最后,我把它简化为这段代码:
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"payload" ofType:@"txt"]];
id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
Run Code Online (Sandbox Code Playgroud)
使用NSZombieEnabled,这会在第三行(解析发生的地方)崩溃应用程序并记录:
*** -[CFString retain]: message sent to deallocated instance 0x758afa0
Run Code Online (Sandbox Code Playgroud)
内容payload.txt是:
[
{
"created_at":"2013-02-15T23:46:02-05:00",
"description":"Take out the Big Gun sounded simple enough, except the Strogg were waiting. You, and a few marines like you, are the lucky ones. You've made it down in one piece and are still able to contact the fleet. The Gravity Well, the Strogg's …Run Code Online (Sandbox Code Playgroud) 我有一个iOS应用程序需要处理来自Web服务的响应.响应是包含序列化JSON对象的序列化JSON字符串,如下所示:
"{ \"name\" : \"Bob\", \"age\" : 21 }"
Run Code Online (Sandbox Code Playgroud)
请注意,此响应是JSON 字符串,而不是JSON对象.我需要做的是反序列化字符串,以便我得到这个:
{ "name" : "Bob", "age" : 21 }
Run Code Online (Sandbox Code Playgroud)
然后我可以用+[NSJSONSerialization JSONObjectWithData:options:error:]它将其反序列化为一个NSDictionary.
但是,我该如何做到第一步呢?也就是说,我如何"unescape"字符串,以便我有一个序列化的JSON对象? +[NSJSONSerialization JSONObjectWithData:options:error:]仅当顶级对象是数组或字典时才有效; 它不适用于字符串.
我最终编写了自己的JSON字符串解析器,我希望它符合RFC 4627的2.5节.但我怀疑我忽略了一些简单的方法来使用NSJSONSerialization或其他一些可用的方法.
我有一个JObject用作调用RESTful Web服务的模板.这JObject是通过解析器创建的,因为它被用作模板告诉用户端点模式是什么样的,我不得不想办法保留所有属性,这就是为什么我将它们的值默认为null.例如,这就是对象最初的样子:
{
"Foo":{
"P1":null,
"P2":null,
"P3":null,
"P4":{
"P1":null,
"P2":null,
"P3":null,
},
"FooArray":[
{
"F1":null,
"F2":null,
"F3":null,
}
]
},
"Bar":null
}
Run Code Online (Sandbox Code Playgroud)
然后,用户能够填补他们需要单独的领域,如Foo.P2和Foo.P4.P1:
{
"Foo":{
"P1":null,
"P2":"hello world",
"P3":null,
"P4":{
"P1":1,
"P2":null,
"P3":null,
},
"FooArray":[
{
"F1":null,
"F2":null,
"F3":null,
}
]
},
"Bar":null
}
Run Code Online (Sandbox Code Playgroud)
意思是他们只关心这两个领域.现在我想将此模板(JObject)序列化为JSON字符串,但只想要填充的那些字段显示出来.所以我尝试了这个:
string json = JsonConvert.SerializeObject(template,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.我遇到了这个问题,并意识到null对象中的值是一个实际JToken类型,而不是真正的类型null,这是有道理的.但是,在这种非常特殊的情况下,我需要能够摆脱这些"未使用"的字段.我尝试手动迭代节点并删除它们,但这也不起作用.请注意,我使用的唯一托管类型是JObject …
我一直在使用以下代码行来解析Objective-C中的JSON数据,但Swift中的相同内容会使应用程序崩溃.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:_webData
options:kNilOptions
error:&error];
Run Code Online (Sandbox Code Playgroud)
我试过使用NSJSONReadingOptions.MutableContainers但似乎没有用.我已经使用在线发现的各种JSON有效性检查器验证了从Web服务器获取的JSON数据的有效性.
[编辑]我使用的swift代码如下:
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
Run Code Online (Sandbox Code Playgroud)
[UPDATE]
使用let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary解决了这个问题.
你好我是一个NSObject类的类:
ProductDetails *details = [[ProductDetails alloc] init];
details.name = @"Soap1";
details.color = @"Red";
details.quantity = 4;
Run Code Online (Sandbox Code Playgroud)
我想将"details"对象传递给字典.
我做到了,
NSDictionary *dict = [NSDictionary dictionaryWithObject:details forKey:@"details"];
Run Code Online (Sandbox Code Playgroud)
我将此dict传递给另一个执行JSONSerialization检查的方法:
if(![NSJSONSerialization isValidJSONObject:dict])
Run Code Online (Sandbox Code Playgroud)
我在这张支票上遇到了崩溃.我在这里做错了吗?我知道我得到的细节是一个JSON对象,我将它分配给我的ProductDetails类中的属性.
请帮我.我是Objective-C的菜鸟.
我现在试过:
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:(NSData*)details options:kNilOptions error:&error];
Run Code Online (Sandbox Code Playgroud)
我需要的只是将细节转换为NSData的简单方法.
我注意到我的对象里面有一个数组可能就是为什么我尝试的所有方法都抛出异常.然而,由于这个问题变得越来越大,我已经开始了另一个问题线程,在那里我显示了我在对象中获取的数据 - /sf/ask/1335677311/
我有一个json对象:
@interface Order : NSObject
@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;
- (NSMutableDictionary *)toNSDictionary;
...
- (NSMutableDictionary *)toNSDictionary
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];
return dictionary;
}
Run Code Online (Sandbox Code Playgroud)
在字符串中这是:
{
"Title" : "test",
"Weight" : "32",
"OrderId" : "55"
}
Run Code Online (Sandbox Code Playgroud)
我用代码获取字符串JSON:
NSMutableDictionary* str = [o toNSDictionary];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] …Run Code Online (Sandbox Code Playgroud) 我有一些类似的代码(我在这里简化了):
let text = "abc" let iosVersion = UIDevice.currentDevice().systemVersion
let message = ["Text" : text, "IosVersion" : iosVersion]
if NSJSONSerialization.isValidJSONObject(message){
let url = NSURL(string: "http://localhost:3000/api/someapi")
var request = NSMutableURLRequest(URL: url!)
var data = NSJSONSerialization.dataWithJSONObject(message, options: nil, error: nil)
println(data)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = data
let task = session.dataTaskWithRequest(request, completionHandler: nil)
task.resume()
Run Code Online (Sandbox Code Playgroud)
这工作正常,但我希望以可读格式看到JSON,以便我可以将其复制/粘贴到fiddler/curl中,以帮助在服务器端诊断我的API.println(data)上面的行给出了十六进制数据.有任何想法吗?
我正在尝试使用以下字典进行发布请求,该字典转换为JSON
let store = [
"newTask" : [
"project_name": "iOS",
"total_time":0,
"color":"blue"
]
]
Run Code Online (Sandbox Code Playgroud)
我使用以下代码将其序列化,然后使用以下选项发出http-POST请求:
let jsonData = try? JSONSerialization.data(withJSONObject: store)
var request = URLRequest(url: URL(string: "http://localhost:3000/store")!)
request.httpMethod = "POST"
request.httpBody = jsonData
Run Code Online (Sandbox Code Playgroud)
我还使用以下db.json文件运行json-server https://github.com/typicode/json-server
{
"store": [
{
"id": 0,
"ios": {
"project_name": "iOS",
"total_time": 0,
"color": "blue"
}
},
{
"id": 1,
"elm": {
"project_name": "elm",
"total_time": 0,
"color": "blue"
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是db中新添加的项看起来不正确,格式如下:
{
"{\"newTask\":{\"project_name\":\"iOS\",\"total_time\":0,\"color\":\"blue\"}}": "",
"id": 10
},
Run Code Online (Sandbox Code Playgroud)
我不确定为什么它将整个字典序列化为键,然后将空字符串作为值.
更新
以下是将此发布到服务器的代码:
let task = URLSession.shared.dataTask(with: …Run Code Online (Sandbox Code Playgroud) 我试图将一些简单的HTML转换为JSON对象中的字符串值,并且我无法使字符串编码无法转义NSJSONSerialization中的字符串.
示例...我有一个包含一些基本HTML文本的字符串:
NSString *str = @"<html><body><p>Samples / Text</p></body></html>";
Run Code Online (Sandbox Code Playgroud)
期望的结果是JSON,其中HTML为值:
{
"Title":"My Title",
"Instructions":"<html><body><p>Samples / Text</p></body></html>"
}
Run Code Online (Sandbox Code Playgroud)
我正在使用标准技术将NSDictionary转换为包含JSON的NSString:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:str forKey:@"Instructions"];
[dict setObject:@"My Title" forKey:@"Title"];
NSError *err;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&err];
NSString *resultingString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", resultingString);
Run Code Online (Sandbox Code Playgroud)
此方法生成的JSON有效,但HTML包含所有正斜杠转义:
{
"Title":"My Title",
"Instructions":"<html><body><p>Samples \/ Text<\/p><\/body><\/html>"
}
Run Code Online (Sandbox Code Playgroud)
这会在JSON字符串指令中创建无效的HTML.
我想坚持使用NSJSONSerialization,因为我们在我们的框架中的其他地方都使用它,并且在切换到非Apple库之前我已经被烧毁了,因为它们得不到支持.我尝试了很多不同的字符串编码,它们都逃脱了尖括号.
显然\ /是JavaScript中对/字符的有效表示,这就是转义正斜杠的原因(即使StackOverflow文本编辑器也将其转义).请参阅: 使用正斜杠转义json字符串? 还有JSON:为什么正斜线逃脱了?.我只是不希望它这样做,似乎没有办法阻止iOS在序列化时转义字符串值中的正斜杠.
json ×7
ios ×5
swift ×4
nsdictionary ×3
objective-c ×3
c# ×1
cocoa ×1
cocoa-touch ×1
ios6 ×1
json.net ×1
nsstring ×1
struct ×1