2

我在 .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 编码?

4

3 回答 3

1

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

例如,一个空格会变成_x0020_.

于 2013-07-23T14:57:10.613 回答
1

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

如果您有任何进一步的疑问,请告诉我。

于 2013-08-19T05:11:48.323 回答
0

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

于 2013-07-24T10:03:54.337 回答