Newtonsoft中Json和Xml的转换

    var user = new Dictionary<string, object>
        {
            {"CompanyName","Epoint" },
            {"UserName","Ellis" },
            {"Address",new Dictionary<string,string>
                {
                    {"Country","China"},
                    {"Province","JiangSu"},
                    {"City","SuZhou" }
                }
            },
            {"PhoneNumber",new object[]
                {
                    new Dictionary<string,string>
                    {
                        {"Type","Phone" },
                        {"Number","0512-58972850" }
                    },
                    new Dictionary<string,string>
                    {
                        {"Type","Fax" },
                        {"Number","0512-58975860" }
                    }
                }
            }
        };

        //object 转 json
        string json = JsonConvert.SerializeObject(user);

        //json 转xml 
        string xml = JsonConvert.DeserializeXNode(json, "Root", true).ToString();

        //xml 转json
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(xml);
        string jsontext = JsonConvert.SerializeXmlNode(doc);

        //json转object
        dynamic anotnerUser = JsonConvert.DeserializeObject<dynamic>(jsontext);
        string anotherJson = JsonConvert.SerializeObject(anotnerUser);
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容