【发布时间】:2018-03-22 13:00:54
【问题描述】:
我在从 json 文件中获取我想要的值时遇到了一些麻烦。我正在使用简单的json。它看起来像这样:
[
{
"BUTT LIFT (BRIDGE)": [
{
"Main Muscle Worked": "Glutes",
"Sport": "No",
"Force": "Push",
"Level": "Beginner",
"mucle_heatmap": "http://assets.bodybuilding.com/images/trackers/exercise/heatmap/14.gif",
"female_image_end": "http://www.bodybuilding.com/exercises/exerciseImages/sequences/99/Female/l/99_2.jpg",
"female_image_start": "http://www.bodybuilding.com/exercises/exerciseImages/sequences/99/Female/l/99_1.jpg",
"guide": [
"Lie flat on the floor on your back with the hands by your side and your knees bent. Your feet should be placed around shoulder width. This will be your starting position.",
"Pushing mainly with your heels, lift your hips off the floor while keeping your back straight. Breathe out as you perform this part of the motion and hold at the top for a second.",
"Slowly go back to the starting position as you breathe in."
],
"male_image_start": "http://www.bodybuilding.com/exercises/exerciseImages/sequences/99/Male/l/99_1.jpg",
"Equipment": "Body Only",
"link": "http://www.bodybuilding.com/exercises/detail/view/name/butt-lift-bridge",
"male_image_end": "http://www.bodybuilding.com/exercises/exerciseImages/sequences/99/Male/l/99_2.jpg",
"Other Muscles": "Hamstrings",
"Type": "Strength",
"Mechanics Type": "Isolation"
}
]
},
该文件很大,包含大约 800 个练习。我想要的是映射字符串,例如“Force”、“Level”,但我不确定如何访问它。
这是我目前的代码
public void parse() {
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader(filePath));
JSONArray exerciseList = (JSONArray) obj;
for (int i = 0; i < exerciseList.size(); i++) {
JSONObject jsonObj = (JSONObject) exerciseList.get(i);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
这会导致获取整个 JSON 文件。
【问题讨论】:
-
TBH JSON 似乎做得不太好,这可能就是您遇到麻烦的原因。目前,您的
jsonObj将是一个对象,该对象将具有诸如"BUTT LIFT (BRIDGE)"之类的字段,其值将是一个数组,其中包含一个具有许多字段(例如级别和力)的对象。这对于它所描述的内容来说似乎太复杂了,尽管一个更大的例子可以解释为什么需要这种复杂性。我想您需要做的下一步是通过索引访问您的jsonObj的字段,因为它们的名称各不相同:将您的jsonObj处理为Map并通过getEntries浏览其字段