Parsing NSString to get data out
I have this code...
NSData* myData = producedData;
NSLog(@"Contents of myData: %@", myDat开发者_Python百科a);
The log prints
{ "id" = ""; "level" = "level_1"; "handle" = test; }
How do I get the values for id and level and handle out of this? The original data is a NSString*.
Thanks!
Is it JSON? Use Stig Brautaset's JSON parser http://code.google.com/p/json-framework/
You aren't showing the code that actually obtains the data object, nor are you showing any code related to an NSString.
Are you just assigning a string (producedData
) to your myData
variable? That won't create a data object; for one thing, it wouldn't know what encoding to use to encode the string's characters into bytes, and more importantly, copying a pointer from one variable to another (which is what myData = producedData
does—the variables do not contain the objects themselves, only pointers to them) does not change anything about what the pointer points to. The object will remain a string, even though you told the compiler that myData
would point to a data object. The compiler should be warning you about this; you should heed and fix those warnings.
myData
definitely is not a data object; if it were, its description of itself would be a hex dump. It is either a string or a dictionary.
The output you showed matches the syntax that an NSDictionary uses to describe itself. On the other hand, the object could be a string containing such a description. (This latter case is what you're expecting.)
If you have a dictionary: You're done! The object is already parsed.
If you have a string: Send it a propertyList
message, which will parse the string as a property list and return whatever value is represented in it, which, in this case, will be a dictionary.
精彩评论