How to convert JSON to XML or XML to JSON?

后端 未结 13 1291
借酒劲吻你
借酒劲吻你 2020-11-22 05:43

I started to use Json.NET to convert a string in JSON format to object or viceversa. I am not sure in the Json.NET framework, is it possible to convert a string in JSON to X

13条回答
  •  一个人的身影
    2020-11-22 06:18

    You can do these conversions also with the .NET Framework:

    JSON to XML: by using System.Runtime.Serialization.Json

    var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
        Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));
    

    XML to JSON: by using System.Web.Script.Serialization

    var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));
    
    private static Dictionary GetXmlData(XElement xml)
    {
        var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
        if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
        else if (!xml.IsEmpty) attr.Add("_value", xml.Value);
    
        return new Dictionary { { xml.Name.LocalName, attr } };
    }
    

提交回复
热议问题