简体   繁体   中英

Stuck with parsing json data in Java

I hope someone might be able to help me. I am trying to parse following json file:

{
"seminar":[{
    "categoryid": "1",
    "cpe": "13",
    "inventory": [
        "Discussion",
        "Value x",
        "Value y"
    ],
    "teachers": [{
        "titel": "Dipl.-Ing.",
        "company": "XY",
        "name": "Test",
        "id": "3"
    }]
}]
}    

I am lost with parsing the teachers data in...

private static final String TAG_TEACHERS = "teachers";
private static final String TAG_TITLE = "title";

for(int i = 0; i < seminar.length(); i++){
JSONObject c = seminar.getJSONObject(i);

teachers = c.getJSONArray(TAG_TEACHERS);
for(int z = 0; z < teachers.length(); z++){                 
JSONObject d = teachers.getJSONObject(z);
String title  = d.getString(TAG_TITLE);
Log.d("JSONParsingActivity", title);

I get the error System.err(1010): org.json.JSONException: Value null at teachers of type org.json.JSONObject$1 cannot be converted to JSONArray.

What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?

Seems you are using wrong tag. teachers = c.getJSONArray(TAG_DOZENTEN);

Shouldn't it be TAG_teachers instead of TAG_DOZENTEN?

This might not be a answer to your specific problem but anyway. Do you need to parse this manually? Why not use a mapper, like Jackson for example.

http://jackson.codehaus.org/0.9.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html

Much smoother!

You can parse given JSON String as:

JSONObject jObject  = new JSONObject("YOUR_JSON_STRING");

JSONArray jArrseminar = jObj.getJSONArray("seminar");
for(int i = 0; i < jArrseminar.length(); i++){
    JSONObject jobject = jArrseminar.getJSONObject(i);

    String strcategoryid=jobject.getString("categoryid");
    String strcpe=jobject.getString("cpe");

    JSONArray jArrinventory = jobject.getJSONArray("inventory");
    for(int j = 0; j < jArrinventory.length(); j++){

        // access all inventory value here
    }


    JSONArray jArrteachers = jobject.getJSONArray("teachers");
    for(int j = 0; j < jArrteachers.length(); j++){
        JSONObject jobjectteachers = jArrteachers.getJSONObject(i);

        // access all teachers value here
    String strtitel=jobjectteachers.getString("titel");
    String strcompany=jobjectteachers.getString("company");
    String strname=jobjectteachers.getString("name");
    String strid=jobjectteachers.getString("id");
    }
}

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