2011-07-25 50 views
0

我有这个简单的类:解析简单的JSON和负载的简单Java对象

class element{ 
    public int id; 
    public String name; 
} 

这个JSON文件:

[ 
     { 
      "id": 1, 
      "name": "water" 
     }, 
     { 
      "id": 2, 
      "name": "fire" 
     } 
... 
    ] 

如何加载这个JSON名单中?有人可以为我建议一个好的JSON库吗?我可以在android中使用Jar吗?

回答

1

对此很容易。这里是完整的代码

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

public List<element> generateList() 
{ 
    String jsonString = "[{\"id\": 1,\"name\": \"water\"},{\"id\": 2,\"name\": \"fire\"}]"; 
    JSONArray json = null; 
    List<element> mElementList = new ArrayList<element>(); 
    try { 
     json = new JSONArray(jsonString); 
    } catch (JSONException je) { 
     Log.e("TAG", "Json Exception" + je.getMessage()); 
     return; 
    } 
JSONObject jsonObject = null; 
    element ele = null; 
    for (int i = 0; i < json.length(); i++) { 
     try { 
      jsonObject = json.getJSONObject(i); 
          ele = new element(); 

          if(jsonObject.has("id")) 
          { 
           ele.id = jsonObject.getString("id") 
          }  

          if(jsonObject.has("name")) 
          { 
           ele.name = jsonObject.getString("name") 
          }  

      mElementList.add(ele); 
     } catch (JSONException jee) { 
      Log.e("TAG", "" + jee.getMessage()); 
     } 

    } 
      return mElementList; 
    } 
3

您还可以使用内置的org.json库在Android中,你的情况下,你可以使用:

List<Element> elements = new LinkedList<Element>(); 
JSONArray arr = new JSONArray(jsonString); 
JSONObject tempObj; 
Element tempEl; 
for(int i = 0; i < arr.length(); i++){ 
    tempObj = arr.getJSONObject(i); 
    tempEl = new Element(); 
    tempEl.id = tempObj.getInt("id"); 
    tempEl.name = tempObj.getString("name"); 
    elements.add(tempEl); 
} 

,你会得到元素的列表。

+0

您设置了tempEl.id两次! –

+0

aww抱歉,现在修复,谢谢:) – ayublin