2

这是我正在尝试的两个示例查询(在应用程序中,我使用 JSON 作为输出数据,但这有助于格式化):

强制失败:胡言乱语

尝试:堆栈溢出

运行它确实会拉回数据,并且我知道我正在寻找的区域在 jObject["query"]["pages"] 中。所以我注意到在失败中,页面名称/属性/无论是“-1”并且查询有效的内容都会为您提供该主题的唯一 ID。

这是我目前拥有的代码:

JObject excerpt = JObject.Parse(reader.ReadToEnd());
if ((string) excerpt["query"]["pages"] == "-1")
    return null;
result.Excerpt = (string)excerpt["query"]["pages"]["extract"];

它在 if 检查中失败了,我很确定它最终也会在 Excerpt 中失败。

  1. 如何检查“页面”中的项目以查看它是否称为“-1”?

  2. 事先不知道页面的pageid,如何进入查询成功的item?

4

1 回答 1

1

如果您在 JSON.NET 中有一个 JSON 字典,则可以将其视为属性的集合 ( JProperty)。您可以在该集合上使用 LINQ 方法Single()来从中获取唯一的属性。我认为检查页面是否确实丢失的更好方法是检查其missing属性(或者,检查它是否具有excerpt)。整个代码可能如下所示:

private static string GetExtract(string json)
{
    var excerpt = JObject.Parse(json);
    var pageProperty = (JProperty)excerpt["query"]["pages"].Single();

    var page = (JObject)pageProperty.Value;

    if (page["missing"] != null)
        return null;

    return (string)page["extract"];
}

但就个人而言,在这种情况下,我更喜欢使用 XML 而不是 JSON。使用 XML,该方法看起来像(它比 JSON 版本长,但也更简单,我认为这是一个优点):

private static string GetExtractXml(string xml)
{
    var document = XDocument.Parse(xml);

    var page = document
        .Element("api")
        .Element("query")
        .Element("pages")
        .Elements("page")
        .Single();

    if (page.Attribute("missing") != null)
        return null;

    return (string)page.Element("extract");
}
于 2012-09-24T12:41:37.940 回答