繁体   English   中英

无法使用JSON将字符串值从C#传递到JavaScript

[英]Cannot pass string value from c# to JavaScript using JSON

我正在使用Windows Phone的Apatch Cordova插件开发WindowsPhone App。 我需要将参数从C#层传递给JavaScript层,然后使用c#层中的PluginResult和格式化的字符串,并在JavaScript层的cordovaCommandResult插件中使用JSON.parse()函数(cordova.js文件。)但是,当尝试传递字符串值时,发生异常“语法错误:无效字符”。
如何传递字符串值,以便JSON.parse()将成功解析它?

这是我的代码:

C#层:

public void GetConfiguration(string sensorName)
{
    PluginResult result = new PluginResult(PluginResult.Status.OK,GetConfiguration());
    DispatchCommandResult(result); 
}

public override string GetConfiguration()
{
    string config = String.Format("\"unit\":{0},\"exponent\":{1},\"frequency\":{2}",
                        unit, 
                        exponent.ToString("0.0", CultureInfo.InvariantCulture), 
                        frequency.ToString("0.0", CultureInfo.InvariantCulture));

    return "{" + config + "}";
}

其中unit是一个字符串变量,它会导致异常。

JavaScript层:cordova.js

调用GetConfiguration函数:

getConfiguration: function (successCallback, errorCallback, args) {            
    var win = function (result) {
        successCallback(result);
    };

    var fail = errorCallback && function (code) {
        errorCallback(code);
    };

    exec(win, fail, "SensorsManager", "GetConfiguration", args);      
},

解析从c#层返回的结果:

  define("cordova/plugin/windows8/CordovaCommandResult", function (require,exports,
  module) {
    var cordova = require('cordova');
    var channel = require('cordova/channel');

    // singular WP callback function attached to window,
    //status is used to determine if it is a success or error
    module.exports = function (status, callbackId, args, cast) {

    if (status === "backbutton") {
        // do not detach backbutton event, as we need to be able to catch exceptions
        cordova.fireDocumentEvent("backbutton", undefined, true);
        return "true";
    }
    else if (status === "resume") {
        cordova.fireDocumentEvent('resume');
        return "true";
    }
    else if (status === "pause") {
        cordova.fireDocumentEvent('pause');
        return "true";
    }

    var parsedArgs;

    try {
        parsedArgs = JSON.parse(args);
    }
    catch (ex) {
        return;
    }

    var safeStatus = parseInt(status, 10);
        if (safeStatus === cordova.callbackStatus.NO_RESULT ||
            safeStatus === cordova.callbackStatus.OK) {
            cordova.callbackSuccess(callbackId, parsedArgs, cast);
        }
        else {
            cordova.callbackError(callbackId, parsedArgs, cast);
        }
    };
});

实际上您创建的JSON是不正确的。首先使用jsonlint.com验证您准备的JSON

更重要的一点是:1)您作为响应发送回的内容类型是什么。如果您使用第三方库创建Json,然后直接从服务器以text / json的形式发送内容类型,则更好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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