如何在Objective-C中将Xcode中的特定响应转换为JSON格式?
Got it, that string you're working with is actually in the old OpenStep-style ASCII property list format—it's what you get when you print an NSDictionary with description in Objective-C, not valid JSON. Luckily, you don't have to manually hack the string to fix it; Foundation has built-in tools to handle this cleanly.
The Recommended Approach: Use NSPropertyListSerialization
This framework is designed to parse exactly this kind of plist string, then we can convert the resulting dictionary straight to JSON. Here's a step-by-step implementation:
// First, make sure your input string is complete (yours was missing a closing }) NSString *rawPlistString = @"{ \"abc\" = \"lmn\"; \"def\" = \"pqr\"; object = { \"object1\" = { obj = 1; obj2 = ABC; }; \"object2\" = { obj3 = 0; obj4 = LMN; }; }; }"; // Convert the string to NSData NSData *plistData = [rawPlistString dataUsingEncoding:NSUTF8StringEncoding]; // Parse the plist data into an NSDictionary NSError *parseError = nil; NSDictionary *resultDict = [NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListImmutable format:nil error:&parseError]; if (!parseError && resultDict) { // Now convert the dictionary to valid JSON NSError *jsonError = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:resultDict options:NSJSONWritingPrettyPrinted // Optional: makes JSON human-readable error:&jsonError]; if (!jsonError && jsonData) { NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"Converted JSON:\n%@", jsonString); // Use jsonString however you need } else { NSLog(@"Failed to convert to JSON: %@", jsonError.localizedDescription); } } else { NSLog(@"Failed to parse plist string: %@", parseError.localizedDescription); }
Why This Works:
NSPropertyListSerializationnatively understands thekey = value;syntax of OpenStep plists, even handling unquoted keys/values (likeobj = 1orobj2 = ABC) correctly.- Once you have an
NSDictionary, converting to JSON is trivial withNSJSONSerialization—it handles all the quote placement, colon replacement, and structure formatting automatically.
Manual String Manipulation (Not Recommended)
If for some reason you can't use the plist parser, you could do string replacements, but this is error-prone (especially with nested objects or edge cases):
- Replace all instances of
=with: - Replace all instances of
;with, - Add quotes around unquoted keys and string values (you'll need to distinguish numeric values from strings to avoid quoting numbers like
1or0)
This approach is fragile, so stick with the framework method unless you have no other choice.
内容的提问来源于stack exchange,提问作者HSBP

