无法将JSON转换为XML。

4

我可以帮您将JSON字符串转换为XML格式。 1)我的JSON字符串是:

[  
       {  
          "QuizTitle":"asdf",
          "QuizImage":"",
          "QuizCategory":"0",
          "QuizTags":"asdf",
          "question":[  
             [  
                {  
                   "QuestionType":"1",
                   "QuestionTitle":"asdf",
                   "questionOption":[  
                      {  
                         "QuestionOptionValue":"sdf",
                         "QuestionOptionIsRight":"0"
                      },
                      {  
                         "QuestionOptionValue":"asdf",
                         "QuestionOptionIsRight":"1"
                      }
                   ]
                }
             ],
             [  
                {  
                   "QuestionType":"2",
                   "QuestionTitle":"sdfdsf",
                   "questionOption":[  
                      {  
                         "QuestionOptionValue":"asdf",
                         "QuestionOptionIsRight":"0"
                      },
                      {  
                         "QuestionOptionValue":"asdf",
                         "QuestionOptionIsRight":"1"
                      }
                   ]
                }
             ]
          ]
       }
    ]

2) 我的C#代码是:

XmlDocument doc = JsonConvert.DeserializeXmlNode(str);

出现以下错误:

Error:--XmlNodeConverter can only convert JSON that begins with an object.

我尝试对 json 进行了一些小的修改,例如删除问题元素中的 [],但没有起作用。

1
你尝试过使用 JsonConvert.DeserializeXmlNode(str,"root"); 吗? - Mohit S
将JSON转换为XML或XML转换为JSON,使用Json.NET进行转换。 - null1941
1
尝试移除最外层的[]。 - afaolek
是的,JsonConvert.DeserializeXmlNode(str,"root"); 对我有效,谢谢。 - user3248761
3个回答

16
根据Mitchell Skurnik评论,您可以使用JsonConvert.DeserializeXmlNode(JSONString, "root");。如果您的数据是一个数组,则需要像这样做:JsonConvert.DeserializeXmlNode("{"Row":" + json + "}", "root").ToXmlString(),否则您将会得到一个“XmlNodeConverter can only convert JSON that begins with an object.”异常。- Mitchell Skurnik,2015年2月17日1:11

1
我尝试了JsonConvert.DeserializeXmlNode("{"Row":" + json + "}", "root").ToXmlString();,对我很有效,谢谢。 - Francisco Fischer

0

当数组中只有一个值时,此方法有效。该方法不支持在父节点上存在多个数组。


0
<pre> public static string GetXMLFromJson(string jsonString)
        {
             string parentNote="Person";
            XDocument doc = (XDocument)JsonConvert.DeserializeXNode("{\""+ parentNote + "\":" + json + "}", "DocumentElement");
            return doc.ToString();
        } </pre>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接