我正在遍历一个 Json 文件,似乎只得到空值。如您所见,我正在尝试使用 index.html 访问它们。另外,我的整数很有趣,因为当我从 json 值中使用 Integer.parseInt 时它不喜欢。
JSON:
{
"people": [
{
"name": "Kelly",
"age": 50,
"sex": "f",
"illness": "Allergies"
},
{
"name": "Josh",
"age": 40,
"sex": "m",
"illness": "Sleep Apnea"
},
{
"name": "Brad",
"age": 20,
"sex": "m",
"illness": "Heart Disease"
}
]
}
爪哇:
import java.io.FileReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class FileLoader {
@SuppressWarnings("unchecked")
public static void main(String args[]) {
JSONParser parser = new JSONParser();
int count = 0;
try {
Object obj = parser.parse(new FileReader(
"Consumers.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = (JSONArray) jsonObject.get("people");
if(array.size() > 0) {
while (count < array.size()) {
答案编辑
JSONObject people = (JSONObject) array.get(count);
String name = (String) people .get("name");
int age = (Integer) people .get("age");
String sex = (String) people .get("sex");
String illness = (String) people .get("illness");
完成编辑
JSONObject people = (JSONObject) jsonObject.get(count);
String name = (String) jsonObject.get("name");
int age = (Integer) jsonObject.get("age");
String sex = (String) jsonObject.get("sex");
String illness = (String) jsonObject.get("illness");
System.out.println("\nPeople List " + count + ": ");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Sex: " + sex);
System.out.println("Illness: " + illness);
count++;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
我只需要读取文件,但读取嵌套数组时遇到问题。所有值都返回 null。我将此构建为一个 Maven 项目。