简体   繁体   English

使用Java在JSON中的另一个数组中获取数组值

[英]Get array value inside another array in JSON using Java

This is my JSON format这是我的 JSON 格式

{
 "personalData": [
   "firstName": "John",
   "lastName": "Doe",
   "hobby": ["Hiking", "Running", "Swimming"] 
 ]
}

How I can get each element inside "hobby"我如何在“爱好”中获取每个元素

This is my existing code that return all item这是我现有的返回所有项目的代码

JSONObject jsonObject = new JSONObject(classJSON.getJSON(getActivity()));
JSONArray jsonArray = jsonObject.getJSONArray("personalData");
JSONObject data = jsonArray.getJSONObject(0);
data.getString("firstName")
// This will return "John"
data.getString("lastName")
// This will return "Doe"
data.getString("hobby")
// This will return ["Hiking", "Running", "Swimming"]
// How I can access each element in "hobby" like how I can get the element in first index.

There's quite a bit wrong with what you currently have.你目前拥有的东西有点不对劲。

For instance, your json won't parse because you're defining an array within personalData but you're filling it with key value pairs, which is only allowed within an object.例如,您的 json 不会解析,因为您在个人数据中定义了一个数组,但是您正在用键值对填充它,这仅允许在对象中使用。

In reality, your json should look like this:实际上,您的 json 应该如下所示:

{
 "personalData": {
   "firstName": "John",
   "lastName": "Doe",
   "hobby": ["Hiking", "Running", "Swimming"] 
 }
}

Given that this is a JSONObject and not a JSONArray, you'll have to replace this:鉴于这是一个 JSONObject 而不是 JSONArray,您必须替换它:

JSONArray jsonArray = jsonObject.getJSONArray("personalData");
JSONObject data = jsonArray.getJSONObject(0);

With this:有了这个:

JSONObject data = jsonObject.getJSONObject("personalData");

At which point, you'll be able to extract the hobby array like so:此时,您将能够像这样提取爱好数组:

data.getJSONArray("hobby")

I'm not sure if you've done any testing, but data.getString("hobby") should have thrown a JSONException because it's a JSONArray, not a string.我不确定您是否进行过任何测试,但data.getString("hobby")应该抛出 JSONException,因为它是 JSONArray,而不是字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM