Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
245 views
Welcome To Ask or Share your Answers For Others

1 Answer

working solution

JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {

    jsonObject = (JSONObject) parser.parse(new FileReader("E:\json.txt"));

    out.println("<br>"+jsonObject);


    JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
    // for row output 1
    for(Object o: from_excel){
        out.println("<br>"+o);
    }
    // for row output 2
    Iterator iterator = from_excel.iterator();
    while (iterator.hasNext()) {
        out.println("<br>"+iterator.next());
    }
    // for item output 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("Error: "+e);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...