XML、JSON的相互轉化

一、XML

       XML,是指可擴展標記語言,其作用主要用來傳輸和存儲數據,而HTML主要用來顯示數據。XML標籤並未被預定義,這意味着,XML標籤都是自定義的。故而,當需要調用第三方接口時(參數爲XML形式),我們需要知道第三方的xml標籤、層結構。通過XML,數據能夠存儲在獨立的XML文件中,而通過js代碼,就可以讀取一個外部XML文件。
       XML文檔形成了一種樹結構,由根到幹再到枝葉。這意味着,XML文檔必須含有根元素,就像樹必須有根一樣,且根元素是所有其他元素的父元素。xml文檔中的元素之間的關係可以用家族關係來形容。
      在 XML 中,省略關閉標籤是非法的。所有元素都必須有關閉標籤。
      XML元素也可擁有屬性,但其屬性值必須加引號,且特定的屬性名在同一個元素標記中只能出現一次。
       

         XML用於將數據組織爲一棵樹,DOM(文檔對象模型)通過解析XML文檔,爲XML在邏輯上建立一個樹模型,樹的節點是一個個的對象。
         

二、JSON

   JSON語法是JS語法的子集。   

  • 數據在名稱/值對中
  • 數據由逗號分隔
  • 花括號保存對象
  • 方括號保存數組

    JSON實例--創建包含JSON語法的JS字符串

    var txt = '{ "employees" : [' + '{ "firstName":"Bill" , "lastName":"Gates" },' + '{ "firstName":"George" , "lastName":"Bush" },' + '{ "firstName":"Thomas" , "lastName":"Carter" } ]}';

    

由於 JSON 語法是 JavaScript 語法的子集,JavaScript 函數 eval() 可用於將 JSON 文本轉換爲 JavaScript 對象。

eval() 函數使用的是 JavaScript 編譯器,可解析 JSON 文本,然後生成 JavaScript 對象。必須把文本包圍在括號中,這樣才能避免語法錯誤:

       var obj = eval ("(" + txt + ")");
 

關於JSON,最重要的是理解它是一種數據格式,不是一種編程語言。雖然具有相同的語法形式,但JSON 並不屬於js。畢竟JSON只是一種數據格式,不單單js可以使用

JSON中沒有變量的概念!!!
//json,它是一種使用普通文本來表示簡單數據結構的標準,它使用雙引號來描述字符串,
//例如:
"this is a simple json string"
//使用方括號來描述列表
//例如:
[2,5,56]
//使用花括號來描述對象(鍵值對的集合)
{"key":"value"}
//何爲Collection+json?
//Collection+json是一個用於在Web上發佈資源的可搜索列表的標準。JSON將約束建立在普通文本上,
//而Collection+json則將約束建立在JSON上,這意味着它可以僅僅提供一個json對象
//例如:{}
//但是又不僅僅是一個對象,這個對象還必須擁有一個成爲collection的屬性,該屬性可以映射到另一個對象
//例如:{"collection":{}}
//而該“collection”對象應該具有一個稱爲items的屬性,該屬性映射到一個列表
//例如:{"collection":{"items":[]}}
//在items列表屬性中的項目也必須是對象
//{"collection"{"items":[{},{},{}]}}
//如此反覆,最終得到一個高度格式化的文檔
{"collection":
   {
      "key1":"1.2",
      "key2":"dddd",
      "items"[
                {},{},{"datas":[{},{}]}
             ]
   }
}

JSON與JavaScript

JSON數據結構可以解析爲有用的JavaScript對象,而XML數據結構則需要解析成DOM文檔且從中提取數據較爲麻煩。JSON對象中有兩個方法分別將json解析爲JavaScript對象和將JavaScript對象解析爲JSON對象。

<script>
        var book = {
            title: "鋼鐵是怎麼練成的",
            author: [
                "柯察金", "保爾"
            ],
            year: 2005
        };
        var jsonText = JSON.stringify(book);
        console.log(jsonText);
    </script>

<script>
        var book = {
            title: "鋼鐵是怎麼練成的",
            author: [{
                fistName: "保爾",
                lastname:"柯察金"
            }, {
                fistName: "保爾2",
                lastname: "柯察金2"
            }],
            year: 2005
        };
        var jsonText = JSON.stringify(book);
        console.log(jsonText);
    </script>

<script>
        var book = {
            title: "鋼鐵是怎麼練成的",
            author: [{
                fistName: "保爾",
                lastname:"柯察金"
            }, {
                fistName: "保爾2",
                lastname: "柯察金2"
            }],
            year: 2005
        };
        var jsonText = JSON.stringify(book);
        console.log(jsonText);
        var bookCopy = JSON.parse(jsonText);
        console.log(bookCopy);
        console.log(bookCopy.title);
        console.log(bookCopy.author[0].fistName);
    </script>

實際上,JSON.stringify()除了可以序列化JavaScript對象外,還可接收另外兩個參數,這兩個參數用於指定
以不同的方式序列化JavaScript對象
第一個參數:過濾器或是一個數組或函數,即用於過濾屬性

第二個參數:是一個選項,表示是否在JSON字符串中保留縮進
<script>
        var book = {
            title: "鋼鐵是怎麼練成的",
            author: [{
                fistName: "保爾",
                lastname:"柯察金"
            }, {
                fistName: "保爾2",
                lastname: "柯察金2"
            }],
            year: 2005
        };
        var jsonText = JSON.stringify(book,["title","year"],3);
        console.log(jsonText);
        var bookCopy = JSON.parse(jsonText);
        console.log(bookCopy);
        console.log(bookCopy.title);
        console.log(bookCopy.author[0].fistName);
    </script>

<body>
    <input type="text" name="name" id="inp" />
    <script>
        var book = {
            title: "鋼鐵是怎麼練成的",
            author: [{
                fistName: "保爾",
                lastname:"柯察金"
            }, {
                fistName: "保爾2",
                lastname: "柯察金2"
            }],
            year: 2005
        };
        var jsonText = JSON.stringify(book, function (key,value) {
            switch (key) {
                case "title":
                    return value+"New";
                case "author":
                    return value[0]["fistName"] + "Array";
                default:
                    return value;
            }
        });
        console.log(jsonText);
    </script>
</body>

三、XML轉化爲JSON

3.1 示例1--最簡單的一種形式

<datas>
    <DATA>
        <new_deliverynumber>X401-HN1902240001</new_deliverynumber>
        <new_recevicer>徐帥</new_recevicer>
        <new_receivephone>17306207002</new_receivephone>
        <ITEM>
            <new_product_id>152940278</new_product_id>
            <new_seq>2</new_seq>
        </ITEM>
    </DATA>
 </datas>

將上述xml轉換爲json格式:

{
  "datas": {
    "DATA": {
      "new_deliverynumber": "X401-HN1902240001",
      "new_recevicer": "徐帥",
      "new_receivephone": "17306207002",
      "ITEM": {
        "new_product_id": "152940278",
        "new_seq": "2"
      }
    }
  }
}

此時須將json格式轉換爲對象實例,因此應當對json格式進行處理成如下:

{"new_deliverynumber":"X401-HN1902240001","new_recevicer":"徐帥","new_receivephone":"17306207002",
"ITEM":[{"new_product_id":"152940278","new_seq":"2"}]}

處理代碼

public static string MoreJsonFormat(string json)
{

     var jsonStr = json.Substring(17, json.Length - 19);

     if (jsonStr.IndexOf("]}}") < 0)
     {
         jsonStr = jsonStr.Replace(":{", ":[{").Replace("}}", "}]}");
     }
     return jsonStr;
}

注意:對於截取字符串,起始位置從17好理解,對比於需要將json格式處理成的最終結果。那麼爲什麼是減19呢?
以下爲解釋19從何而來

Console.WriteLine(json.LastIndexOf('}'));//166,即json最後一個字符的位置爲166
Console.WriteLine(json.IndexOf('}'));//163

由於substring()方法第二個參數爲截取字符串的長度,前面捨去17個字符串,後面去掉兩個’}‘,加起來正好是19個字符。

代碼附上:
實體類:

    /// <summary>
    /// 出貨通知單
    /// </summary>
    public class TruckloadingModel
    {
        /// <summary>
        /// 出貨通知單號
        /// </summary>
        public string new_deliverynumber { get; set; }
        /// <summary>
        /// 收貨人
        /// </summary>
        public string new_recevicer { get; set; }
        /// <summary>
        /// 收貨電話
        /// </summary>
        /// <summary>
        /// 明細
        /// </summary>
        public List<TruckoloadingLineModel> ITEM { get; set; }
    }
    /// <summary>
    /// 出貨通知單明細
    /// </summary>
    public class TruckoloadingLineModel
    {
        /// <summary>
        /// 調度單號
        /// </summary>
        public string new_dispatchnumber { get; set; }
        /// <summary>
        /// 項次
        /// </summary>
        public string new_seq { get; set; }
        /// <summary>
        /// 產品編碼
        /// </summary>
    }

處理代碼:

 static void Main(string[] args)
        {
            string xml = @"<datas>
             <DATA>
         	    <new_deliverynumber>X401-HN1902240001</new_deliverynumber>
         	    <new_recevicer>徐帥</new_recevicer>
         	    <new_receivephone>17306207002</new_receivephone>
         	    <ITEM>
         		    <new_product_id>152940278</new_product_id>
         		    <new_seq>2</new_seq>
         	    </ITEM>
         	 </DATA>
             </datas>";
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            //Xml格式轉json處理
            string json = JsonConvert.SerializeXmlNode(document);

            //Xml格式轉json處理
            var models = new List<TruckloadingModel>();
           
            var truckloading = new TruckloadingModel();
           truckloading = JsonUtils.DeserializeObject<TruckloadingModel>(MoreJsonFormat(json));
                Console.WriteLine(MoreJsonFormat(json));
                models.Add(truckloading);
            Console.ReadKey();
        }

如果再加一條明細呢?是不是代碼依然可以這樣寫?這時依然需要觀察轉換爲json之後的格式是不是處理方式依然如此!

{
  "datas": {
    "DATA": {
      "new_deliverynumber": "X401-HN1902240001",
      "new_recevicer": "徐帥",
      "new_receivephone": "17306207002",
      "ITEM": [
        {
          "new_product_id": "152940278",
          "new_seq": "2"
        },
        {
          "new_product_id": "152940278",
          "new_seq": "2"
        }
      ]
    }
  }
}

其可轉換爲對象的格式爲:

{"new_deliverynumber":"X401-HN1902240001","new_recevicer":"徐帥","new_receivephone":"17306207002",
"ITEM":[{"new_product_id":"152940278","new_seq":"2"},{"new_product_id":"152940278","new_seq":"2"}]}

觀察而言,截取字符串時,起始位置爲17沒有問題,去掉最後兩個’}‘,剛好。因此,用同一種方式處理沒有問題。

現在可以確定,無論加多少條明細,上述提供的方法皆可使用。那麼,如果是提供兩個data呢?不外乎有如下幾種形式:
示例2:

xml形式一

<datas>
         <DATA>
         	<new_deliverynumber>X401-HN1902240001</new_deliverynumber>
         	<new_recevicer>徐帥</new_recevicer>
         	<new_receivephone>17306207002</new_receivephone>
         	<ITEM>
         		<new_product_id>152940278</new_product_id>
         		<new_seq>2</new_seq>
         	</ITEM>
         	</DATA>
         	 <DATA>
         	<new_deliverynumber>X401-HN1902240002</new_deliverynumber>
         	<new_recevicer>蓉姐</new_recevicer>
         	<new_receivephone>18361337238</new_receivephone>
         	<ITEM>
         		<new_product_id>23232334</new_product_id>
         		<new_seq>3</new_seq>
         	</ITEM>
         	</DATA>
 </datas>

轉換爲json

{
  "datas": {
    "DATA": [
      {
        "new_deliverynumber": "X401-HN1902240001",
        "new_recevicer": "徐帥",
        "new_receivephone": "17306207002",
        "ITEM": {
          "new_product_id": "152940278",
          "new_seq": "2"
        }
      },
      {
        "new_deliverynumber": "X401-HN1902240001",
        "new_recevicer": "徐帥",
        "new_receivephone": "17306207002",
        "ITEM": {
          "new_product_id": "152940278",
          "new_seq": "2"
        }
      }
    ]
  }
}

將json處理爲可轉換爲對象的數據

[{"new_deliverynumber":"X401-HN1902240001","new_recevicer":"徐帥","new_receivephone":"17306207002",
"ITEM":[{"new_product_id":"152940278","new_seq":"2"}]},
{"new_deliverynumber":"X401-HN1902240002","new_recevicer":"蓉姐","new_receivephone":"18361337238",
"ITEM":[{"new_product_id":"678789520","new_seq":"3"}]}]

觀察後得到,截取字符串時,從17開始沒有問題,19也沒有問題,明顯適合第一種處理方式。但值得注意的是,此時是批量傳輸,應用數組來接收。直接上圖

models = JsonUtils.DeserializeObject<List<TruckloadingModel>>(MoreJsonFormat(json));

還有一種情況,就是多個主檔下又有多個明細。這裏不再展現,直接給代碼:
 

 static void Main(string[] args)
        {
            string xml = @"<datas>
            <DATA>
         	<new_deliverynumber>X401-HN1902240001</new_deliverynumber>
         	<new_recevicer>徐帥</new_recevicer>
         	<new_receivephone>17306207002</new_receivephone>
         	    <ITEM>
         		    <new_product_id>152940278</new_product_id>
         		    <new_seq>2</new_seq>
         	    </ITEM>
                        	
           </DATA>
<DATA>
         	<new_deliverynumber>X401-HN1902240001</new_deliverynumber>
         	<new_recevicer>徐帥</new_recevicer>
         	<new_receivephone>17306207002</new_receivephone>
         	    <ITEM>
         		    <new_product_id>152940278</new_product_id>
         		    <new_seq>2</new_seq>
         	    </ITEM>
                        	
           </DATA>
 </datas>";
            XmlDocument document = new XmlDocument();
            document.LoadXml(xml);
            //Xml格式轉json處理
            string json = JsonConvert.SerializeXmlNode(document);
            Console.WriteLine("json格式:");
            Console.WriteLine("*****************************************************************");
            Console.WriteLine(json);
            Console.WriteLine("*****************************************************************");

            //Xml格式轉json處理
            var models = new List<TruckloadingModel>();
            if (json.IndexOf("[{") > 0 && json.IndexOf("}]") > 0&&json.IndexOf("}]}]")>0)
            {
                json = "splitmark" + json.Substring(18);
                Console.WriteLine(("[" + Regex.Split(Regex.Split(json, "splitmark")[1], "]}}")[0] + "]").Replace(":{", ":[{").Replace("}}", "}]}"));
                models = JsonUtils.DeserializeObject<List<TruckloadingModel>>(("[" + Regex.Split(Regex.Split(json, "splitmark")[1], "]}}")[0] + "]").Replace(":{", ":[{").Replace("}}", "}]}"));
            }
            else if (json.IndexOf("}}]}}")>0)
            {
                models = JsonUtils.DeserializeObject<List<TruckloadingModel>>(MoreJsonFormat(json));
            }
            else
            {
                var truckloading = new TruckloadingModel();
                Console.WriteLine(MoreJsonFormat(json));
                truckloading = JsonUtils.DeserializeObject<TruckloadingModel>(MoreJsonFormat(json));

                models.Add(truckloading);
            }
            Console.ReadKey();
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章