如何在序列化为XML时处理JSON键中的空格?

时间:2013-07-23 14:51:01

标签: c# .net xml json json.net

我在.NET 4.0应用程序中使用Json.NET,以便将JSON RESTful响应转换为XML。如果JSON子键有空格,我遇到了将JSON转换为XML的问题。

到目前为止,我能够转换大多数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编码?

3 个答案:

答案 0 :(得分:1)

您可以拨打XmlConvert.EncodeName,使用_来转义任何无效字符。

例如,空格将变为_x0020_

答案 1 :(得分:1)

此问题与how to validate JSON string before converting to XML in C#

相同

如果您有任何疑问,请告诉我。

答案 2 :(得分:0)

您不能拥有包含空格的XMLElement名称。您需要使用Underscore或任何其他元素替换该空间。如果这对您不可行,请尝试将该值作为该节点的属性。 我希望这是有道理的。