初始化

            Car car = new Car();
            car.root = new Root();
            car.root.list = new List();
            car.root.name = "海德格";
            car.root.data = "救我";
            for (int f = 0; f < 10; f++)
            {
                car.root.list.Add(f.ToString());
            }

class to json, then to xml

            
            string jsonText = JsonConvert.SerializeObject(car);
            XDocument xdoc = (XDocument)JsonConvert.DeserializeXNode(jsonText);

存成xml檔案

            SaveFileDialog save = new SaveFileDialog();
            if ((bool)save.ShowDialog())
            {
                xdoc.Save(save.FileName);
            }

xml to json, then to class

            string json =  JsonConvert.SerializeXNode(xdoc);
            Car reverseCar = JsonConvert.DeserializeObject(json);

class 結構

    public class Root
    {
        public string name { get; set; }
        public string data { get; set; }
        public List list;
    }
    public class Car
    {
        public Root root { get; set; }
    }

// 會有問題的地方是class最外層只能有一個屬性(Root),不能有多個屬性在最上層

 

<?xml version="1.0" encoding="utf-8"?>
<root>
<list>0</list>
<list>1</list>
<list>2</list>
<list>3</list>
<list>4</list>
<list>5</list>
<list>6</list>
<list>7</list>
<list>8</list>
<list>9</list>
<name>海德格</name>
<data>救我</data>
</root>

 

完整版範例:(可解決有時不是Array或List的問題及有時有屬性或沒有屬性值的問題)

Github: XML-to-Json-then-to-Obj

 

參考資料:

1.http://stackoverflow.com/questions/814001/json-net-convert-json-string-to-xml-or-xml-to-json-string

2.http://dotnetqueries.wordpress.com/2013/07/18/json-root-object-has-multiple-properties-the-root-object-must-have-a-single-property-in-order-to-create-a-valid-xml-document-consider-specifing-a-deserializerootelementname/

3.http://msdn.microsoft.com/en-us/library/bb345830(v=vs.110).aspx

4.http://json2csharp.com/

5.http://stackoverflow.com/questions/14198134/deserialize-json-not-working-with-json-net (解決List或Array 在json只有一個的問題)

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(0) 人氣()