【问题标题】:Issues Using JSON.Net to serialize from JSON to XML - C#使用 JSON.Net 将 JSON 序列化为 XML 的问题 - C#
【发布时间】:2017-08-28 18:04:00
【问题描述】:

我正在尝试使用 AJAX 将 JSON 对象从客户端发送到服务器。我想获取 JSON 并将其序列化为 xml 并将其存储在 SQL Server 中。

我正在执行 POST 并使用以下命令将 JSON 作为字符串发送:

    var Full_JSON = products_json[product_id];
    var Message = "";

    if (FULL_JSON == null) {
        Message = "No Products_JSON!";
    }

    if (Message.length == 0) {
        $.ajax({
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",  
            url: "/Query.asmx/InsertXMLJSON",  
            data: "{'JSON':'" + JSON.stringify(Full_JSON) + "'}",
            success: function (Record) {
                if (Record.d == true) {
                    console.log("AJAX Success: " + JSON.stringify(Record));
                }
                else {
                    console.log("AJAX Fail: " + JSON.stringify(Record));
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log("Status: " + textStatus);
                console.log("Error: " + errorThrown);
            }
        })
    }

然后我获取传递的“JSON”字符串并调用:

public static bool InsertXMLJSON(string UserEmail, string Time, string Product, string JSON)
{
    System.Xml.XmlDocument xmlJSON = JsonConvert.DeserializeXmlNode(JSON, "root");
}

当它被调用时,我得到如下所示的异常:

解析值后遇到意外字符:Q. 路径 'Calculations.1.Calculation_Logic',第 1 行,位置 4167。

这是遇到该字符的 JSON 字符串的 sn-p:

\"Calculation_Logic\":\"Math.round((products_json[product_id][\"Questions\"][1][\"Answer\"])/(products_json[product_id][\"Questions\"][3][\"Answer\"]))\"

我注意到方括号内引号的转义似乎是问题的一部分。如果我删除引号,它会很好地解析它。

知道为什么这会导致问题吗?

【问题讨论】:

    标签: c# json ajax xml json.net


    【解决方案1】:

    在我看来,您对名为 Full_JSON 的简单字符串变量进行了字符串化。您尝试发送它而不是 JSON.stringify(Full_JSON)?如果没有完整的代码示例,很难理解您到底在字符串化什么,但这可能是原因。例如:

    var str = '{"2003":{"1":{"2":["test"],"3":["test2"]}}}';
    var obj = {"2003":{"1":{"2":["test"],"3":["test2"]}}};
    
    //this one looks very similar to your problem
    console.log( JSON.stringify(str) );  // {\"2003\":{\"1\":{\"2\":[\"test\"],\"3\":[\"test2\"]}}} 
    
    //and this one is correct use of this component
    console.log( JSON.stringify(obj) );  // {"2003":{"1":{"2":["test"],"3":["test2"]}}} 
    

    【讨论】:

    • 感谢您的推荐。我已经为 AJAX 上传了一个代码 sn-p。我在 JSON 对象上直接调用 JSON.stringify。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 2016-04-03
    • 2011-02-02
    • 1970-01-01
    相关资源
    最近更新 更多