I have the packet data coming in on a recieveEvent delegate.
getting dictionary of packet.dataAsJSON works, and doing an NSLog on that looks like this
args = (
{
id = "123";
name = "John Doe";
status = "Yeah";
}
};
= "JoinedChat";
First, I'm confused as to why it has '=' and ';' instead of ':' and ','
Second, when I getObjectAtKey:#"args", I don't get another dictionary of 3 objects , I get a dictionary of 1 object...and there's no keys...if I parse it as an Array, and get objectsAtIndex:0, I'm getting 3 objects but not dictionaries, I'm trying to access the data in there, but it isn't working. help please
I use the below code in my app:-
NSData *data = [packet.data dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
then use "json" variable and reload the table. This is working in my chat application.
Related
Reading this file city.list.us.json.gz (uncompressed) gets an error (3840) doing:
NSString * path = [mb pathForResource:#"city.list.us" ofType:#"json" inDirectory:#"JSON"];
NSString * string = [NSString stringWithContentsOfUTF8File:path];
NSData * data = [string dataUsingEncoding:NSASCIIStringEncoding];
NSLog(#"isValidJSONObject:%#", [NSJSONSerialization isValidJSONObject:data] ? #"Yes" : #"No");
NSError * bobo = nil;
id blob = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&bobo];
[NSApp presentError:bobo];
which reads ok - length 1873878 bytes, looks ok in vi (set list), but does not yield a non-nil object.
A head -4 of the file shows:
{"_id":4070245,"name":"Jones Crossroads","country":"US","coord":{"lon":-85.484657,"lat":31.21073}}
{"_id":4344544,"name":"Vernon Parish","country":"US","coord":{"lon":-93.183502,"lat":31.11685}}
{"_id":4215307,"name":"Pennick","country":"US","coord":{"lon":-81.55899,"lat":31.313}}
{"_id":5285039,"name":"Black Bear Spring","country":"US","coord":{"lon":-110.288139,"lat":31.386209}}
To my un-expert JSON eyes, it appears this is a file of cites, has an object per line with 4 values (_id,name,country,coord), last an object containing 2 values (lat,lon).
Also tried NSASCIIStringEncoding for the NSData conversion but no joy.
Any ideas?
That's not valid JSON. It's a large number of JSON dictionaries but they are not related to each other.
Most likely the expected JSON (an array of dictionaries) is supposed to look like
[{"_id":4070245,"name":"Jones Crossroads","country":"US","coord":{"lon":-85.484657,"lat":31.21073}},
{"_id":4344544,"name":"Vernon Parish","country":"US","coord":{"lon":-93.183502,"lat":31.11685}},
{"_id":4215307,"name":"Pennick","country":"US","coord":{"lon":-81.55899,"lat":31.313}},
{"_id":5285039,"name":"Black Bear Spring","country":"US","coord":{"lon":-110.288139,"lat":31.386209}}]
I wrapped the whole text in square brackets [] and added commas at the end of each line.
NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.
I have search a lot ,i did found many answers, but not the specific one i need-which is so simple.
I want to take 2 different NSString that the user type, and create a json from them to send to server .
I wrote this :
-(id)stringToJason:(NSString*)stringData
{
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
return json;
}
But there is something i dont get. this return 1 nsstring as json.
How would i take 2 different NSStrings, and create from them together ,the json ?
Lets say: userName:me (when each one is comes from text field)
json should look like :
"Username": "me",
"Firstname": "r",
"Lastname": "k",
If you're wanting to produce JSON that looks like:
{
"Username":"me",
"Firstname":"r",
"Lastname":"k"
}
Where r and k are values taken from the textfields, you could write a method along the lines of this:
-(NSData*)jsonFromFirstName:(NSString*)firstName andLastName:(NSString*)lastName
{
NSDictionary* dic = #{#"Username" : #"me", #"Firstname" : firstName, #"Lastname" : lastName};
// In production code, _check_for_errors!
NSData* json = [NSJSONSerialization dataWithJSONObject:dic options:0 error:nil];
return json;
}
You would call this method, passing the r (firstName) and k (lastName) values to it. It would construct a dictionary that has the structure of the desired JSON, with the desired values. You'd then use NSJSONSerialization's -dataWithJSONObject:options:error selector to convert the dictionary into a JSON data object (stored in an NSData object). You then have the data to send to the server!
The dictionary created in the first line of the method could be expanded as much as you desired, and you could even pass in non-strings (such as numbers, arrays, or even other dictionaries!).
I want to display the json data obtained as:
NSDictionary *detail = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&e];
and want to display it in UITextView(contact):
self.contact.text = [NSString stringWithFormat:#"%#",[detail valueForKey:#"Contact"];
But, I get the output as follows:
("Washington St, SD, CA")
detail is as follows:
(
{
Contact = "Washington St, SD, CA";
Id = 1;
Name = BJs;
}
)
I understand since it returns an array, But how do I display it in a string without the round brackets?
For dictionary access, you should ideally be using objectForKey:, not valueForKey: (which has to do with key-value coding).
I don't know what your original JSON looks like, but if it is like:
{"Contact": "Washinton St, SD, CA", ...}
Then this should work fine. If not (i.e. it actually is an array in JSON), you might want to extract the first element (with [... objectAtIndex:0], or joining the elements, or something else depending on your application).
I am currently trying to work with json and objective-c however having a bit of difficulty. The following is the json that is being returned
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
I am able to check that the response is coming back and the key is sethostname however no matter what I try I cannot get for example the value of status or statusmsg. Can anyone point me in the right location. The following is basic code I am using to check that sethostname is returned.
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
NSLog([res description]);
NSArray *arr;
arr = [res allKeys];
if ([arr containsObject:#"sethostname"])
{
NSLog(#"worked");
}
When in doubt, write down the structure of your JSON data. For example:
{
sethostname = (
{
msgs = "Updating Apache configuration\nUpdating cPanel license...Done. Update succeeded.\nBuilding global cache for cpanel...Done";
status = 1;
statusmsg = "Hostname Changed to: a.host.name.com";
warns = (
);
});
}
(which is in NeXTSTEP property list format, actually) means that you have a top-level dictionary. This top-level dictionary contains a key called sethostname whose value is an array. This array is comprised of dictionaries, each dictionary having a set of keys: msgs, status, statusmsg, warns. msgs has a string value, status has a number value, statusmsg has a string value,warns` has an array value:
dictionary (top-level)
sethostname (array of dictionaries)
dictionary (array element)
msgs (string)
status (number)
statusmsg (string)
warns (array)
??? (array element)
Having understood this structure, your code should look like:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&myError];
if (!res) { // JSON parser failed }
// dictionary (top-level)
if (![res isKindOfClass:[NSDictionary class]]) {
// JSON parser hasn't returned a dictionary
}
// sethostname (array of dictionaries)
NSArray *setHostNames = [res objectForKey:#"sethostname"];
// dictionary (array element)
for (NSDictionary *setHostName in setHostNames) {
// status (number)
NSNumber *status = [setHostName objectForKey:#"status"];
// statusmsg (string)
NSString *statusmsg = [setHostName objectForKey:#"statusmsg"];
…
}
Why not use the simplest JSON method - [myString jsonValue];
It's part of this JSON framework for objective-c
I don't think if ([arr containsObject:#"sethostname"]) is going to work, because the results array is not going to contain that exact object. It might contain an object with the same content, but it won't be the SAME object.
As jtbandes wrote, you need to log the actually output. NSLog both res and arr and see what you have.