问题
I am trying to get specific value from json file. Here is my json file.
{
"set_with_ratio": {
"tweaks_es": "7",
"ratio": {
"brand_defined_sets_ratio": {
"default": {
"desktop": {
"16": "85",
"11": "95",
"19": "10",
"12": {
"2": "50"
}
}
},
"rentals": {
"desktop": {
"16": "75",
"11": "45",
"12": {
"2": "10"
}
}
}
}
}
}
}
how can I get data for x.set_with_ratio.ratio.brand_defined_sets_ratio.default.desktop.11
this json path. I am trying this code in Java.
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("sample.json"));
String id = jsonObject.get("set_with_ratio").toString();
System.out.println(id);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
Here I get the total json file but cannot manage to get expected result.
回答1:
Try this
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
public class JavaTest {
@Test
public void name() {
JSONParser jsonParser = new JSONParser();
try {
//Parsing the contents of the JSON file
JSONObject jsonObject = (JSONObject) jsonParser.parse("{\n" +
" \"set_with_ratio\": {\n" +
" \"tweaks_es\": \"7\",\n" +
" \"ratio\": {\n" +
" \"brand_defined_sets_ratio\": {\n" +
" \"default\": {\n" +
" \"desktop\": {\n" +
" \"16\": \"85\",\n" +
" \"11\": \"95\",\n" +
" \"19\": \"10\",\n" +
" \"12\": {\n" +
" \"2\": \"50\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"rentals\": {\n" +
" \"desktop\": {\n" +
" \"16\": \"75\",\n" +
" \"11\": \"45\",\n" +
" \"12\": {\n" +
" \"2\": \"10\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}");
String id = ((JSONObject) ((JSONObject) ((JSONObject) ((JSONObject) ((JSONObject) jsonObject.get("set_with_ratio"))
.get("ratio"))
.get("brand_defined_sets_ratio"))
.get("default"))
.get("desktop"))
.get("11" +
"").toString();
System.out.println(id);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Result is 95
回答2:
Try this :
JSONTokener parser = new JSONTokener(new FileReader("sample.json"));
JSONObject jsonObject = new JSONObject(parser);
String id = jsonObject.getJSONObject("set_with_ratio").getJSONObject("ratio").getJSONObject("brand_defined_sets_ratio").getJSONObject("default").getJSONObject("desktop").getString("11");
Library used : org.json
来源:https://stackoverflow.com/questions/61766375/how-can-i-get-multiple-json-data-from-json-file-one-by-one