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



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

到目前为止,我能够转换大多数JSON响应。

下面是示例响应以及我用来生成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编码?

这个问题与如何在C#中转换为XML之前验证JSON字符串相同

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

您可以调用XmlConvert.EncodeName,它将使用_ s转义任何无效字符。

例如,一个空间将变成_x0020_

XMLElement Name中不能有空格。您需要将空格替换为Undercore或任何其他元素。如果这对您来说不可行,请尝试将该值作为该节点的属性。我希望这是有道理的。

相关内容

  • 没有找到相关文章

最新更新