N
N
Nikolay Baranenko2016-09-25 20:08:47
Java
Nikolay Baranenko, 2016-09-25 20:08:47

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"
    }
  ]
}

I'm trying to parse this JSON in Java this way using the org.json.simple.* library
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());
        }

but somewhere I make the simplest mistake ....
How to parse this JSON correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikolay Baranenko, 2016-09-26
@drno-reg

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 question

Ask a Question

731 491 924 answers to any question