【发布时间】:2014-09-19 14:24:31
【问题描述】:
我必须使用JSON 在PHP 中输入encode 字符串。而且我无法在任何地方找到编码字符串的示例。每个人都对数组进行编码。你在 PHP 和解码的 obj c 中有任何例子吗?
【问题讨论】:
-
你读过this吗?
-
是的,但它是这个字符串中的数组
标签: php ios objective-c
我必须使用JSON 在PHP 中输入encode 字符串。而且我无法在任何地方找到编码字符串的示例。每个人都对数组进行编码。你在 PHP 和解码的 obj c 中有任何例子吗?
【问题讨论】:
标签: php ios objective-c
你试过这个吗?
<?php
$stringSingleElement = new array($yourstringdata) ;
json_encode(stringSingleElement[0]);
?>
【讨论】:
一般来说,当你想在 PHP 中进行 json 编码时,你可以使用json_encode。您的根对象必须是数组(或字典)才能生成有效的 json 字符串。
另请注意,json_encode 直接与字符串一起使用时不会报错(但它不会产生有效的 json 字符串)。
echo json_encode(array('a' => 'test1', 'b' => 'test2'));
// {"a":"test1","b":"test2"}
echo json_encode(array('c'));
// ["c"]
echo json_encode('d');
// "d"
Objective-c 代码
// Let's assume that jsonString is a NSString containing {"a":"test1","b":"test2"}
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(@"dictionary string: %@", dictionary[@"a"]); // Output: test1
【讨论】: