如何提取"提取物"来自JSON的属性?

时间:2016-12-25 13:32:05

标签: java json org.json

我正在尝试从以下链接读取JSON数据:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Russell%27s_paradox

我可以使用:

读取pages属性中的整个数据
DateTimeOffset myDateTimeOffset = myCalendarDatePicker.Date ?? default(DateTimeOffset);
DateTime myDateTime = myDateTimeOffset.DateTime;
var formatArray = myDateTime.GetDateTimeFormats();
string desiredDateTimeFormat = formatArray[index];

我想从"提取"中获取数据。属性接下来是上面提到的链接,我无法做到。我是新手,我无法找到任何资源来学习这一点。

我尝试了以下代码但是我收到了JSONException。

JSONObject data=(JSONObject)new JSONTokener(IOUtils.toString(new URL("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Russell%27s_paradox"))).nextValue();
String pageName=data.getJSONObject("query").getString("pages");
System.out.println(pageName);

帮助。

2 个答案:

答案 0 :(得分:1)

您尝试解析的JSON的结构是:

{
  "batchcomplete": "",
  "query": {
    "normalized": [
      {
        "from": "Russell's_paradox",
        "to": "Russell's paradox"
      }
    ],
    "pages": {
      "46095": {
        "pageid": 46095,
        "ns": 0,
        "title": "Russell's paradox",
        "extract": "..."
      }

也就是说,pages内的query是一个对象,而不是一个数组。 然后,extract位于另一个嵌套对象中,键为46095。 你可以这样进入extract字段:

JSONObject pages = data.getJSONObject("query").getJSONObject("pages");
for (String key : pages.keySet()) {
    String def = pages.getJSONObject(key).getString("extract");
    System.out.println(def);
}

答案 1 :(得分:0)

使用 node JS,您可以通过其属性名称获取,还可以根据 JSON 对象的深度通过 for 循环或递归导航到内部节点。以下是使用 for 循环处理 JSON 的 2 级属性/数据的简单示例:

const jsonStudent = '{"name":"Mond S","fields":{"Age":12,"Class":"Grad 8","School":"In Town"}}';
 get_JSON_Data ();

function println (msg)
{
  if (DEBUG) {
    var jsonDate = (new Date()).toJSON();
    console.log( jsonDate + ' myParser ' + msg);
  }
}

function get_JSON_Data ()
{
  DEBUG = true;
  var obj = JSON.parse(jsonStudent); // This obj is json object made from string 
  for (var k in obj)
  {
    println ("Got Key " + k + " = " + obj [k]);
    if (typeof (obj [k]) == 'object')
    {
      var felds = obj [k];
      for (var f in felds)
        println ( "    Got fields attr " + f + "   = " + felds [f] + ", direct from obj " + obj[k][f]);
    }  
  }
}

==== 输出将是

2020-12-26T13:06:47.645Z myXMLParser Got Key name = Mond S
2020-12-26T13:06:47.649Z myXMLParser Got Key fields = [object Object]
2020-12-26T13:06:47.649Z myXMLParser     Got fields attr Age   = 12 ,direct from obj 22
2020-12-26T13:06:47.649Z myXMLParser     Got fields attr Class   = Grad 8 ,direct from obj Grad 8
2020-12-26T13:06:47.649Z myXMLParser     Got fields attr School   = In Town ,direct from obj In Town