简体   繁体   English

在Java for Android中解析JSON数据

[英]Parsing JSON data in Java for Android

I hope someone might be able to help me. 我希望有人可以帮助我。 I am trying to parse following json file: 我正在尝试解析以下json文件:

{"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_DOZENTEN);
    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. 我收到错误System.err(1010):org.json.JSONException:类型为org.json.JSONObject $ 1的教师的值null无法转换为JSONArray。

What did I do wrong? 我做错了什么? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. 据我从JSON文档了解,教师是JSON数组,而不是对象。 Is somebody able to help me? 有人可以帮助我吗?

You have an extra (trailing) comma in teachers (after "3"). 您的教师中有一个额外的(尾随)逗号(“ 3”之后)。 Not allowed in JSON. 不允许在JSON中使用。 Remove it and see if that helps. 删除它,看看是否有帮助。

If your JSON is really of the form: 如果您的JSON确实是以下形式:

{ ... }, { ... }, { ... }, ...

This is invalid JSON 这是无效的JSON

The root enclosure must either be a single object (in {} ) or an array (in [] ). 根附件必须是单个对象(在{} )或数组(在[] )。

If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it. 如果您打算发送对象数组,则只需用方括号将整个对象包装成一个数组,然后从中创建一个JSONArray对象。

So it must be like this 所以一定是这样

[ { ... }, { ... }, { ... }, ... ]

You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems. 您还需要确保没有多余的逗号,不加括号的括号等。使用JSONLint或其他类似的JSON格式检查器可以节省一些时间来查找语法问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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