I have to encode string in PHP using JSON. And I have a problem with finding anywhere examples of encoding strings. Everybody encodes arrays. Do you have any example of this in PHP and in obj c of decoding?
Asked
Modified
11 years, 3 months ago
Viewed
84 times
Part
of PHP and Mobile Development Collectives
-
Did you read this?Compass– Compass2014-09-19 14:29:02 +00:00Commented Sep 19, 2014 at 14:29
-
Yes but it's array in this stringMikey– Mikey2014-09-19 14:30:43 +00:00Commented Sep 19, 2014 at 14:30
Add a comment
|
2 Answers
Have u tried this one .
<?php
$stringSingleElement = new array($yourstringdata) ;
json_encode(stringSingleElement[0]);
?>
1 Comment
Daniel Wondyifraw
Hi , mickey how about trying place that string into a single element of an array then access it like $thatarray[0] thing ..?
Generally speaking when you want to json encode something in PHP, you can use json_encode. Your root object must be an array (or dictionary) in order to produce a valid json string.
Note also that json_encode doesn't complain when you use it directly with strings (but it doesn't produce a valid json string).
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 code
// 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