如何用数组中的多个对象解析json?

时间:2014-07-09 06:04:26

标签: android parsing android-json jsonexception

JSONArray有以下结构:

{

    "People":[
        {
            "006MST21IND":{
                "desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP",
                "attribute":"1,b_“F”ELEMENT / c_`G' ELEMENT;2,b_“F”ELEMENT / c_`G' ELEMENT;3, b_“F”ELEMENT / c_`G' ELEMENT"
            }
        },
        {
            "006MST22IND":{
                "desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP",
                "attribute":"1,b_“F”ELEMENT / c_`G' ELEMENT;2,b_“F”ELEMENT / c_`G' ELEMENT;3, b_“F”ELEMENT / c_`G' ELEMENT"
            }
        }
    ]

}

我正在尝试,但它提供以下例外,

org.json.JSONException: Value [{"006MST21IND":{"attribute":"1,b_�F�ELEMENT \/ c_`G' ELEMENT;2,b_�F�ELEMENT \/ c_`G' ELEMENT;3, b_�F�ELEMENT \/ c_`G' ELEMENT","desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP"}},{"006MST22IND":{"attribute":"1,b_�F�ELEMENT \/ c_`G' ELEMENT;2,b_�F�ELEMENT \/ c_`G' ELEMENT;3, b_�F�ELEMENT \/ c_`G' ELEMENT","desc":"MST21 BAL. PR. THERMOSTATIC STEAM TRAP"}}] 
at People of type org.json.JSONArray cannot be converted to JSONObject

代码是:

我将json数据保存在文件中并从中获取,

File root = Environment.getExternalStorageDirectory();
File jsonFile = new File(root, "jsonFile.txt");
FileInputStream stream;
String jsonStr = null;
stream = new FileInputStream(jsonFile);



FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

jsonStr = Charset.defaultCharset().decode(bb).toString();


stream.close();

然后通过使用jsonStr,我使用以下逻辑......

JSONObject jsonObj = new JSONObject(jsonStr);

JSONObject jsonObj1 = jsonObj.getJSONObject("People");
JSONArray myJson=jsonObj1.getJSONArray("006MST21IND");

if (myJson!=null && myJson.length()!=0) {


    for(int i=0;i<myJson.length();i++)
    {
        JSONObject obj2 = myJson.getJSONObject(i);

        desc = obj2.getString("desc");
        attribute = obj2.getString("attribute");

        Log.e("Desc:", desc);
        Log.e("Attribute:", attribute);
    }

}

我尝试但失败了。

2 个答案:

答案 0 :(得分:0)

pepole不是对象它是阵列
    JSONArray jsonarr = jsonObj.getJSONArray(&#34; People&#34;);

答案 1 :(得分:0)

您尝试将JSONobject作为JSONarray获取并将JSONarray作为JSONobject获取。请尝试以下操作:

 try {
        JSONObject jsonObj = new JSONObject(jsonStr);

        JSONarray arry = jsonObj.getJSONarray("People")

        if (arry.length()!=0) {

        for(int i=0;i<arry.length();i++)
        {
           JSONObject obj2 = arry.getJSONObject(i);

           desc = obj2.getString("desc");
           attribute = obj2.getString("attribute");

           Log.e("Desc:", desc);
           Log.e("Attribute:", attribute);
        }
     }

   } catch(Exception e){
       //Catch Error Here
 }