【问题标题】:Get the count of entries from a json file从 json 文件中获取条目数
【发布时间】:2016-08-05 06:14:17
【问题描述】:

我正在尝试从虚假的 api 调用中获取 json 数据,并且需要获取其中的项目数(以便将来我可以调用实际的 restful 服务)。我无法获得 json 中的部门数量。我在这里期望结果为 4(int)。

我无法获取以下代码的字符串值(json):

String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);

请在下面找到整个代码:

String json = client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType.TEXT_PLAIN).get(String.class);

JSONObject jsnobject = new JSONObject(json);

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
} 

JSON 示例:

{
"Department":
[
    {"SectionId":"1","SectionName":"Childrens Wear"},
    {"SectionId":"2","SectionName":"Womens Wear"},
    {"SectionId":"3","SectionName":"F&A"},
    {"SectionId":"1","SectionName":"Mens Wear"}
]
}

我是 java 和 api 的新手。

谢谢,

【问题讨论】:

  • "locations""Department"
  • 请在您的问题中解决您的实际问题。不要提出一个问题,并在得到回答后然后在 cmets 中向该答案提出您真正的问题。
  • 您无法获取字符串值,因为您的 JSON 路径在应该有空格 (' ') 的地方有 %20"file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json" 应该是 "file:///C:/Program Files (x86)/apache-tomcat-8.0.35/webapps/GetProducts.json"

标签: java arrays api count restful-url


【解决方案1】:

您在代码中使用了不正确的键,或者您发布了不正确的 JSON 示例。您使用 locations 作为密钥 incode,但是在示例 JSON 中没有针对该密钥的值。您需要使用Department 作为密钥。

JSONArray jsonArray = jsnobject.getJSONArray("Department");

【讨论】:

  • 嗨,Harshil,那是我的错。它实际上是代码中的“部门”。我没有得到代码的输出:client.target("file:///C:/Program%20Files%20(x86)/apache-tomcat-8.0.35/webapps/GetProducts.json").request(MediaType .TEXT_PLAIN).get(String.class);
  • 请更新问题以包括更正和您得到的实际结果。
猜你喜欢
  • 1970-01-01
  • 2021-12-10
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多