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!).
Related
I have the following situation:
NSDictionary *params = #{
#"Checkout" : #{
#"conditions" : #{#"Checkout.user_id" : #1},
#"order" : #{#"Checkout.id" : #"DESC"}
},
#"PaymentState" : #[],
#"Offer" : #[]
};
This dictionary contains params for a webservice request passing a JSON string with the webservice URL. I get the JSON string using NSJSONSerialization class, like this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
The problem is: jsonString "keys" is ordered differently from the original params dictionary keys order, like this:
{
"Offer":[],
"PaymentState":[],
"Checkout":{
"conditions":{"Checkout.user_id":6},
"order":{"Checkout.id":"DESC"}
}
}
That is, the "PaymentState" and "Offer" keys come first in jsonString, and i need maintain
the original order. This is very important, like this:
{
"Checkout":{
"conditions":{"Checkout.user_id":6},
"order":{"Checkout.id":"DESC"}
},
"Offer":[],
"PaymentState":[]
}
So guys, how can i do that??
I use OrderedDictionary from CocoaWithLove whenever I need to keep the order of my dictionary keys.
Basically, OrderedDictionary contains an NSMutableDictionary and an NSMutableArray for the keys inside it, to keep track of the order of the keys. It implements the required methods for subclassing NSDictionary/NSMutableDictionary and just "passes" the method call to the internal NSMutableDictionary.
According to the JSON spec a JSON object is specifically unordered. Every JSON library is going to take this into account. So even when you get around this issue for now, you're almost certainly going to run into issues later; because you're making an assumption that doesn't hold true (that the keys are ordered).
While NSDictionary and Dictionary do not maintain any specific order for their keys, starting on iOS 11 and macOS 10.13, JSONSerialization supports sorting the keys alphabetically (see Apple documentation) by specifying the sortedKeys option.
Example:
let data: [String: Any] = [
"hello": "world",
"a": 1,
"b": 2
]
let output = try JSONSerialization.data(withJSONObject: data, options: [.prettyPrinted, .sortedKeys])
let string = String(data: output, encoding: .utf8)
// {
// "a" : 1,
// "b" : 2,
// "hello" : "world"
// }
Given the following JSON payload I would like to extract "023" from keyB->key2:
JSON Payload:
{
"keyA" : {"lon": 139, "lat" : 35},
"keyB" : [ {"key1" : "value", "key2" : "023"} ]
}
This is the code I apply:
NSDictionary * subResults = jsonResult[#"keyB"];
NSLog(#"VALUE: %#", [subResults valueForKey:#"key2"])
However the value is printed as following:
VALUE: (
023
)
I want to get rid of the brackets "(". Am I approaching the extraction in the wrong way?
First, your json as given is not valid son :( you have a quote to many. If we escape it like this:
{"keyA":{"lon":139,"lat":35},"keyB":[{"key1":"value\" clouds","key2":"023"}]}
Then, it's ok.
Now, what you have here is an son object, containing 2 keys (A and B). And KeyB is associated with a json Array
meaning :
jsonResult[#"keyB"];
Does not return a NSDictionnary but a NSArray, containing 1 NSDictionary.
Now if you try to get the value "023", you should use
NSString str = jsonResult[#"keyB"][0][#"key2"]; // return "023"
and maybe
int twentyThree = str.intValue;
The brackets show the value you want is inside an array.
NSData strAsData = …;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:strAsData options:0 error:nil];
NSArray *subResults = jsonResult[#"keyB"];
NSDictionary *subSubResults = subResults[0];
NSLog(#"VALUE: %#", subSubResults[#"key2"]);
Because the array only has one item you can use a call to -lastObject or -firstObject
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.
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 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).