开发者

Parse simple json and load in simple java objects

开发者 https://www.devze.com 2023-03-22 21:26 出处:网络
I have this simple class: class element{ public int id; public String name; } and this JSON file: [ { \"id\": 1,

I have this simple class:

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

and this JSON file:

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

How do I load this JSON in List? Can somebody suggest to me a开发者_Go百科 good JSON library for this? Can I use Jar in android ?


You can also use built in org.json library in android, for your case you can use:

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);
}

And you will get a list of elements.


Try Jackson; it can handle this and much more.


Its very easy to this. Here is the complete code

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;
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消