Nikolay Baranenko Nikolay Baranenko - 2 months ago 14
Java Question

How right parce JSON from file?

I have JSON from file.

{
"from_excel":[
{
"solution":"Fisrt",
"num":"1"
},
{
"solution":"Second",
"num":"2"
},
{
"solution":"third",
"num":"3"
},
{
"solution":"fourth",
"num":"4"
},
{
"solution":"fifth",
"num":"5"
}
]
}


and want to parse list of Solution and Num.

Used lib org.json.simple.*

Try this one


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());
}


What am I doing wrong?

If try to write



JSONObject solutions = (JSONArray) jsonObject.get("from_excel");



enter image description here

If try to write



JSONArray array = obj.getJSONArray("from_excel");



get error
enter image description here

Answer

There is no "solution" array in the JSON. "from_excel" is the array. So your code should look like this :

Object obj = parser.parse(new FileReader("E:\\json.txt"));

    JSONObject jsonObject = (JSONObject) obj;

    out.println(jsonObject.get("from_excel"));

    JSONObject solutions = (JSONArray) jsonObject.get("from_excel");

    Iterator iterator = solutions.iterator();
    while (iterator.hasNext()) {
        out.println(iterator.next());
    }