2013-07-23 19 views
2

我在.NET 4.0應用程序中使用Json.NET以將JSON RESTful響應轉換爲XML。如果JSON子鍵有空格,我遇到將JSON轉換爲XML的問題。如何在序列化爲XML時處理JSON密鑰中的空格?

到目前爲止,我能夠轉換大多數JSON響應。

Here are example responses along with the code which I am using to generate the XML.

{ 
    num_reviews: "2", 
    page_id: "17816", 
    merchant_id: 7165 
} 

在此可以導致一個錯誤的響應:

[ 
    { 
    headline: "ant bully", 
    created_date: "2010/06/12", 
    merchant_group_id: 10126, 
    profile_id: 0, 
    provider_id: 10000, 
    locale: "en_US", 
    helpful_score: 1314, 
    locale_id: 1, 
    variant: "", 
    bottomline: "Yes", 
    name: "Jessie", 
    page_id: "17816", 
    review_tags: [ 
    { 
    Pros: [ 
    "Easy to Learn", 
    "Engaging Story Line", 
    "Graphics", 
    "Good Audio", 
    "Multiplayer", 
    "Gameplay" 
    ] 
    }, 
    { 
    Describe Yourself: [ 
    "Casual Gamer" 
    ] 
    }, 
    { 
    Best Uses: [ 
    "Multiple Players" 
    ] 
    }, 
    { 
    Primary use: [ 
    "Personal" 
    ] 
    } 
    ], 
    rating: 4, 
    merchant_id: 7165, 
    reviewer_type: "Verified Reviewer", 
    comments: "fun to play" 
    }, 
    { 
    headline: "Ok game, but great price!", 
    created_date: "2010/02/28", 
    merchant_group_id: 10126, 
    profile_id: 0, 
    provider_id: 10000, 
    locale: "en_US", 
    helpful_score: 1918, 
    locale_id: 1, 
    variant: "", 
    bottomline: "Yes", 
    name: "Alleycatsandconmen", 
    page_id: "17816", 
    review_tags: [ 
    { 
    Pros: [ 
    "Easy to Learn", 
    "Engaging Story Line" 
    ] 
    }, 
    { 
    Describe Yourself: [ 
    "Frequent Player" 
    ] 
    }, 
    { 
    Primary use: [ 
    "Personal" 
    ] 
    }, 
    { 
    Best Uses: [ 
    "Kids" 
    ] 
    } 
    ], 
    rating: 3, 
    merchant_id: 7165, 
    reviewer_type: "Verified Reviewer", 
    comments: "This is a cute game for the kids and at a great price. Just don't expect a whole lot." 
    } 
    ] 

到目前爲止,我一直在考慮在創建JSON數據映射到C#對象,爲該類生成XML。但是,有沒有辦法保持這種動態?或者有沒有辦法將空間視爲%20編碼?

+0

這不是一個有效的JSON字符串(或者甚至是JavaScript)。如果屬性名稱需要空格,則必須加上引號。要麼修復響應,以便返回有效的字符串,要麼編寫自己的解析器來解析它。 –

回答

1

您可以撥打XmlConvert.EncodeName,這將使用_ s轉義任何無效字符。例如,空格將變爲_x0020_

+0

儘管這很好,但我得到JsonConvert.DeserializeNode()來生成正確的XML的問題。原因是原始源代碼不會嘗試處理空格。 – Hectron

0

您不能擁有帶有空格的XMLElement Name。您需要用Underscore或其他元素替換空間。如果這對您不可行,請嘗試將該值作爲該節點的屬性。 我希望這是有道理的。