当键处于层次结构下时,使用java提取json中键的值

dxpyg8gm  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(367)

我需要从下面的json中提取recordone的值。

{
  "errors": [],
  "data": {
    "paging": {
      "RecordOne": 8,
      "RecordTwo": 9,
      "recordThree": 2,
      "totalNumberOfRecords": 86052
    },
    "products": [
      {
        "testabstract": "test data",
        "authors": "Frank Jr.",
        "invertedauthors": "Frank VJr.",
        "formatCode": "KND"
      }
     ]
   }
}

我使用java作为语言和json对象来实现相同的功能,下面是我使用的:

protected String getTokenValueUnderHeirarchy(String responseString){
        JSONObject json = new JSONObject(responseString);
        String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
        System.out.println("val::"+val);
return val;
    }

我得到的值是val=1,应该是8
如果我尝试寻找具有相同代码的键totalnumberofrecords的值,它将返回正确的值86052
我知道这很愚蠢,但我听不懂。

mfuanj7w

mfuanj7w1#

当我用json示例运行您的代码时,我得到了一个“jsonexception:jsonobject[“recordone”]is not a string”。。。。。但事实并非如此。用双引号将8括起来:“8”返回您期望的值。如果愿意,可以使用其他get方法getint访问该值。
这个测试用例同时解析一个字符串和一个int。它适合你吗?

package org.nadnavillus.test;

import org.json.JSONObject;
import org.junit.Test;

public class TestCase {

    protected String getTokenValueUnderHeirarchy(String responseString) throws Exception {
        JSONObject json = new JSONObject(responseString);
       String val= json.getJSONObject("data").getJSONObject("paging").getString("RecordOne");
        System.out.println("val::"+val);
        return val;
    }

    protected String getTokenValueUnderHeirarchyInt(String responseString) throws Exception {
        JSONObject json = new JSONObject(responseString);
        int val= json.getJSONObject("data").getJSONObject("paging").getInt("RecordTwo");
        System.out.println("val::"+val);
        return String.valueOf(val);
    }

    @Test
    public void testJson() throws Exception {
        String input = "{\"errors\": [], \"data\": {\"paging\": {\"RecordOne\": \"8\", \"RecordTwo\": 9, \"recordThree\": 2, \"totalNumberOfRecords\": 86052}}}";
        String test = this.getTokenValueUnderHeirarchy(input);
        System.out.println(test);
        test = this.getTokenValueUnderHeirarchyInt(input);
        System.out.println(test);
    }
}

相关问题