Loading JSON from String into JSONArray on Android
A few problems I can see:
- You use jsonObj on the first line, which is a JSONObject. Then in the for loop, you use a different object called json. I'm going to assume that these two are the same object. Otherwise, there is information missing from your example.
- JSONObject does not have a method get that takes an integer. There is one that takes a string, so I will assume you meant that one.
- JSONObject.get returns the data corresponding to the key you give it. It returns an Object.
The error you are getting is because you are trying to cast an JSONObject to a Kabelskap.
What I would do is create a helper method like below. Alternatively, you could create a special constructor on the Kabelstap object.
public Kabelskap getKabelskapFromJSON(JSONObject jsonObj)
{
Kabelskap k = new Kabelskap();
String driftsmerking = jsonObj.getString("driftsmerking");
k.setDriftsmerking(driftsmerking);
String addresse = jsonObj.getString("addresse");
k.setAddresse(addresse);
String objektnummer = jsonObj.getString("objektnummer");
k.setObjektNummer(objektnummer);
double spenning = jsonObj.getDouble("spenning");
k.setSpenning(spenning);
// ... and so on for each property.
return k;
}
which can then be used like so:
try {
JSONArray jsonArray = new JSONArray(yourJSONString);
for(int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObj = jsonArray.getJSONObject(i);
Kabelskap k = getKabelskapFromJSON(jsonObj);
// do something with k. eg
System.out.println("Kabelskap@"+i+": "+k);
}
} catch (JSONException e) {
e.printStackTrace();
}
Documentation for JSONObject is here and JSONArray is here.