How to convert JSON to XML or XML to JSON?

后端 未结 13 1096
借酒劲吻你
借酒劲吻你 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

    Cinchoo ETL - an open source library available to do the conversion of Xml to JSON easily with few lines of code

    Xml -> JSON:

    using (var p = new ChoXmlReader("sample.xml"))
    {
        using (var w = new ChoJSONWriter("sample.json"))
        {
            w.Write(p);
        }
    }
    

    JSON -> Xml:

    using (var p = new ChoJsonReader("sample.json"))
    {
        using (var w = new ChoXmlWriter("sample.xml"))
        {
            w.Write(p);
        }
    }
    

    Checkout CodeProject article for some additional help.

    Disclaimer: I'm the author of this library.

    0 讨论(0)
  • 2020-11-22 06:19

    Yes, you can do it (I do) but Be aware of some paradoxes when converting, and handle appropriately. You cannot automatically conform to all interface possibilities, and there is limited built-in support in controlling the conversion- many JSON structures and values cannot automatically be converted both ways. Keep in mind I am using the default settings with Newtonsoft JSON library and MS XML library, so your mileage may vary:

    XML -> JSON

    1. All data becomes string data (for example you will always get "false" not false or "0" not 0) Obviously JavaScript treats these differently in certain cases.
    2. Children elements can become nested-object {} OR nested-array [ {} {} ...] depending if there is only one or more than one XML child-element. You would consume these two differently in JavaScript, etc. Different examples of XML conforming to the same schema can produce actually different JSON structures this way. You can add the attribute json:Array='true' to your element to workaround this in some (but not necessarily all) cases.
    3. Your XML must be fairly well-formed, I have noticed it doesn't need to perfectly conform to W3C standard, but 1. you must have a root element and 2. you cannot start element names with numbers are two of the enforced XML standards I have found when using Newtonsoft and MS libraries.
    4. In older versions, Blank elements do not convert to JSON. They are ignored. A blank element does not become "element":null

    A new update changes this (Thanks to Jon Story for pointing it out): https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm

    JSON -> XML

    1. You need a top level object that will convert to a root XML element or the parser will fail.
    2. Your object names cannot start with a number, as they cannot be converted to elements (XML is technically even more strict than this) but I can 'get away' with breaking some of the other element naming rules.

    Please feel free to mention any other issues you have noticed, I have developed my own custom routines for preparing and cleaning the strings as I convert back and forth. Your situation may or may not call for prep/cleanup. As StaxMan mentions, your situation may actually require that you convert between objects...this could entail appropriate interfaces and a bunch of case statements/etc to handle the caveats I mention above.

    0 讨论(0)
  • 2020-11-22 06:19

    I did like David Brown said but I got the following exception.

    $exception {"There are multiple root elements. Line , position ."} System.Xml.XmlException
    

    One solution would be to modify the XML file with a root element but that is not always necessary and for an XML stream it might not be possible either. My solution below:

    var path = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, @"..\..\App_Data"));
    var directoryInfo = new DirectoryInfo(path);
    var fileInfos = directoryInfo.GetFiles("*.xml");
    
    foreach (var fileInfo in fileInfos)
    {
        XmlDocument doc = new XmlDocument();
        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ConformanceLevel = ConformanceLevel.Fragment;
    
        using (XmlReader reader = XmlReader.Create(fileInfo.FullName, settings))
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                {
                    var node = doc.ReadNode(reader);
                    string json = JsonConvert.SerializeXmlNode(node);
                }
            }
        }
    }
    

    Example XML that generates the error:

    <parent>
        <child>
            Text
        </child>
    </parent>
    <parent>
        <child>
            <grandchild>
                Text
            </grandchild>
            <grandchild>
                Text
            </grandchild>
        </child>
        <child>
            Text
        </child>
    </parent>
    
    0 讨论(0)
  • 2020-11-22 06:23

    Here is a simple snippet that converts a XmlNode (recursively) into a hashtable, and groups multiple instances of the same child into an array (as an ArrayList). The Hashtable is usually accepted to convert into JSON by most of the JSON libraries.

    protected object convert(XmlNode root){
        Hashtable obj = new Hashtable();
        for(int i=0,n=root.ChildNodes.Count;i<n;i++){
            object result = null;
            XmlNode current = root.ChildNodes.Item(i);
    
            if(current.NodeType != XmlNodeType.Text)
                result = convert(current);
            else{
                int resultInt;
                double resultFloat;
                bool resultBoolean;
                if(Int32.TryParse(current.Value, out resultInt)) return resultInt;
                if(Double.TryParse(current.Value, out resultFloat)) return resultFloat;
                if(Boolean.TryParse(current.Value, out resultBoolean)) return resultBoolean;
                return current.Value;
            }
    
            if(obj[current.Name] == null)
                obj[current.Name] = result;
            else if(obj[current.Name].GetType().Equals(typeof(ArrayList)))
                ((ArrayList)obj[current.Name]).Add(result);
            else{
                ArrayList collision = new ArrayList();
                collision.Add(obj[current.Name]);
                collision.Add(result);
                obj[current.Name] = collision;
            }
        }
    
        return obj;
    }
    
    0 讨论(0)
  • 2020-11-22 06:25

    I'm not sure there is point in such conversion (yes, many do it, but mostly to force a square peg through round hole) -- there is structural impedance mismatch, and conversion is lossy. So I would recommend against such format-to-format transformations.

    But if you do it, first convert from json to object, then from object to xml (and vice versa for reverse direction). Doing direct transformation leads to ugly output, loss of information, or possibly both.

    0 讨论(0)
  • For convert JSON string to XML try this:

        public string JsonToXML(string json)
        {
            XDocument xmlDoc = new XDocument(new XDeclaration("1.0", "utf-8", ""));
            XElement root = new XElement("Root");
            root.Name = "Result";
    
            var dataTable = JsonConvert.DeserializeObject<DataTable>(json);
            root.Add(
                     from row in dataTable.AsEnumerable()
                     select new XElement("Record",
                                         from column in dataTable.Columns.Cast<DataColumn>()
                                         select new XElement(column.ColumnName, row[column])
                                        )
                   );
    
    
            xmlDoc.Add(root);
            return xmlDoc.ToString();
        }
    

    For convert XML to JSON try this:

        public string XmlToJson(string xml)
        {
           XmlDocument doc = new XmlDocument();
           doc.LoadXml(xml);
    
           string jsonText = JsonConvert.SerializeXmlNode(doc);
           return jsonText;
         }
    
    0 讨论(0)
提交回复
热议问题