Answer the question
In order to leave comments, you need to log in
How to properly parse JSON from a file (org.json.simple.* library)?
Hello.
This type of JSON is loaded from the file
{
"from_excel":[
{
"solution":"Fisrt",
"num":"1"
},
{
"solution":"Second",
"num":"2"
},
{
"solution":"third",
"num":"3"
},
{
"solution":"fourth",
"num":"4"
},
{
"solution":"fifth",
"num":"5"
}
]
}
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONObject obj_new = (JSONObject) jsonObject.get("from_excel");
JSONArray solution = (JSONArray) obj_new.get("solution");
Iterator iterator = solution.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Answer the question
In order to leave comments, you need to log in
working option
JSONParser parser = new JSONParser();
JSONObject obj;
try {
obj = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));
out.println("<br>"+obj);
JSONObject jsonObject = (JSONObject) obj;
JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// вариант построчного вывода 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// вариант построчного вывода 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// вариант поименного вывода 3
for (int i = 0; i < from_excel.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Ошибка: "+e);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question