简体   繁体   中英

From JavaScript to Objective-C with JSON

I have no idea how to properly 'return' this JSON object (in JavaScript):

function callback() {   
                var points = '{\"points\": [';
                var params = polyline.getLatLngs();

                var i;
                for (i = 0; i < points.length; i++) {
                    params = params.concat('{\"latitude\": ', points[i].lat, ', \"longitude\": ', points[i].lng, '}');
                    if (i < points.length - 1) {
                        params = params.concat(', ');
                    }
                }
                params = params.concat('] }');

                return JSON.parse(params);
            }

I want to catch it with something like (Objective-C):

NSString *s = [self.webView stringByEvaluatingJavaScriptFromString:@"callback();"];

Obviously this results in a NSString, what I really want is NSData to do this (Objective-C):

NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONWritingPrettyPrinted error:&error];

So, how to properly return the JSON?

This should do it:

function callback() {
    var params = polyline.getLatLngs();
    var result = [];
    var i;
    for (i = 0; i < params.length; i++) {
        result.push({latitute: params[i].lat, longitude: params[i].long});
    }

    return JSON.stringify({points: result});
}

Note that JSON.parse generates an object from a string, and JSON.stringify creates a string from an object. No need to do it manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM