-->

Sending string as JSON object

2020-07-22 17:27发布

问题:

I have an assignment that requires me to put a string as a json object and before sending the object i have to put this json object into a http header. This is my code:

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSString *nid = @"";
    NSString *vocab = @"";
    NSString *inturl = @"testoverview";
    NSString *mail = @"chh@fbr.dk";
    NSString *md5pw = @"4d57e7ef1b7c3f431aca424764e9d786";

    NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                    nid, @"nid", 
                                    vocab, @"vocab",
                                    inturl, @"inturl",
                                    mail, @"mail",
                                    md5pw, @"md5pw",nil];


    NSString *json = @"{nid:"",vocab:"",inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";


    NSError *error;



    NSString *url = @"http://udv.taenk.dk/chh/drupal-taenk/services/mobile";


    NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];


    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];

     NSURLConnection *connction = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    FSRemoteExecutor *remote = [[FSRemoteExecutor alloc] init];
    [remote execute:url andHandler:[FSProductTestHandler alloc] JSONString:jsonString JSONData:jsonData Connection:connction];
    [remote connection:connction didReceiveData:jsonData];
    [remote connectionFinishedLoading:connction];

My problem is that i can't use the jsonDictionary with objects and send it, cuz the string format that the service has to receive is this:

"{"nid":"","vocab":"", "inturl":"testoverview", "mail":"", "md5pw":""}"

The dictionary would insert = in the string and that would give me no response from the service.

I want to send a string (json in the code) as dataWithJSONObject:jso, likes this:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:&error];

but i get an error satating this:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'

can anybody help me with this ?

回答1:

But why use use NSJSONSerialization then? You did your own JSON string (NSString *json = @"{nid:"",vocab:"",inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";). Then you don't need to run again a NSJSONSerialization.

Just make a NSData out of your *json (NSString) and then send it to the server.

Make your NSData like this:

NSData *jsonPayload = [json dataUsingEncoding:NSUTF8StringEncoding];


回答2:

First, your string json does not contain the quotation characters you think it does. You have to "escape" a quote in a string with a backslash for it to not terminate the string. Your line:

NSString *json = @"{nid:"",vocab:"",inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";

is being parsed like this:

NSString *json = @"{nid:"
                 ",vocab:"
                 ",inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";

That is, it's three quoted strings in sequence. The compiler concatenates adjacent string literals. So, the effect is this:

NSString *json = @"{nid:,vocab:,inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";

with no embedded quote characters.

What you wanted to write was:

NSString *json = @"{nid:\"\",vocab:\"\",inturl:testoverview, mail:chh@fbr.dk, md5pw:4d57e7ef1b7c3f431aca424764e9d786}";

Can you show the output of:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];

I don't see where you would get an "=" character.


Update:

This code (modified from your question):

NSString *nid = @"";
NSString *vocab = @"";
NSString *inturl = @"testoverview";
NSString *mail = @"chh@fbr.dk";
NSString *md5pw = @"4d57e7ef1b7c3f431aca424764e9d786";

NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                nid, @"nid", 
                                vocab, @"vocab",
                                inturl, @"inturl",
                                mail, @"mail",
                                md5pw, @"md5pw",nil];

NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonData as string:\n%@", resultAsString);

gives this output:

jsonData as string:
{
  "md5pw" : "4d57e7ef1b7c3f431aca424764e9d786",
  "nid" : "",
  "inturl" : "testoverview",
  "mail" : "chh@fbr.dk",
  "vocab" : ""
}

if you use 0 instead of NSJSONWritingPrettyPrinted, it gives:

jsonData as string:
{"md5pw":"4d57e7ef1b7c3f431aca424764e9d786","nid":"","inturl":"testoverview","mail":"chh@fbr.dk","vocab":""}