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;
}
精彩评论