简体   繁体   中英

I have a json object. I want to access in java service. I am trying to parse it

I am using import net.sf.json.JSONObject

My object is like this:

[{
    "courseId": "AUTO_CAD",
    "strDate": "02-04-2012"
 }, {
    "courseId": "CNC_PROG",
    "strDate": "03-04-2012"
}]

Please help me how to access this in java service

//The code that i have tried.

List<JSONObject> jsonList = new ArrayList<JSONObject>(); 
jsonList = (List<JSONObject>) context.get("courseData"); // courseDate is my json object
JSONObject obj = jsonList.get(0); 
Debug.log("courseStartDate ="+ obj.getJSONObject("courseId")); 

//Using this gives me the following error. org.ofbiz.webapp.event.EventHandlerException: Service invocation error (java.lang.String cannot be cast to net.sf.json.JSONObject)

You can do this:

JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
System.out.println(pilot.getString("aKey"));

Here you have an ArrayList yourObject

for (int i = 0; i < yourObject.size(); i++) { 
 System.out.println(yourObject.get(i).getCourseId());
 System.out.println(yourObject.get(i).getStrDate());
}

Have not tested yet the code, but worth a try:

JSONArray courses = new JSONArray(json);

JSONObject first = courses.getJSONObject(0); //Or access in a loop using courses.length()
Debug.log("CourseID: "+ first.getString("courseId"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM