Reputation: 447
I receive this data from HTTP:
[
{
"ID": "1",
"NOME": "Nome 1",
"APELIDO": "Apelido 1",
"CATEGORIA": "1"
},
{
"ID": "2",
"NOME": "Nome 2",
"APELIDO": "Apelido 2",
"CATEGORIA": "1"
}
]
How I can parse this data on Android ID = int
and CATEGORIA = int
?
Upvotes: 0
Views: 324
Reputation: 92
try {
String json = "give the json value here";
JSONArray jsonArray = new JSONArray(json);
for(int i = 0, N = jsonArray.length(); i < N; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
int CATEGORIA = Integer.parseInt(jsonObject.optString("CATEGORIA").toString());
}
}
} catch (JSONException e) {
//handle exception
}
Upvotes: 0
Reputation: 647
Just in-case if you are defining the json then you can change it to: [{"ID":1,"NOME":"Nome 1","APELIDO":"Apelido 1","CATEGORIA":1},{"ID":2,"NOME":"Nome 2","APELIDO":"Apelido 2","CATEGORIA":1}]
As Json supports int type then why to take such values in String. Its better that we directly take them in int.
For converting ID and CATEGORIA to integer, you need to do it manually. As in json data its string, you need to first take it in string and then manually convert it to int by using Integer.parseInt method.
I would suggest to use com.google.gson library for parsing. Below is the model class (Data.java) for Json mentioned by you. You can use Data.parse(stringJson) to get list of Data.
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
public class Data {
/**
* @SerializedName should contain json key name
*/
@Expose
@SerializedName("ID")
private String mId;
@Expose
@SerializedName("NOME")
private String mNome;
@Expose
@SerializedName("APELIDO")
private String mApelido;
@Expose
@SerializedName("CATEGORIA")
private String mCategoria;
public static ArrayList<Data> parse(String json) {
Type listType = new TypeToken<List<Data>>() {
}.getType();
Gson gson = new Gson();
ArrayList<Data> dataList = gson.fromJson(json, listType);
return dataList;
}
}
Upvotes: 1
Reputation: 69035
You can do
JSONArray jsonArray = new JSONArray(data);
for (int i=0; i < jsonArray.length(); i++)
{
try {
JSONObject eachObject = jsonArray.getJSONObject(i);
// Getting items from the json array
int id = eachObject.getInt("ID");
int cattegory = eachObject.getInt("CATEGORIA");
String nome= eachObject.getString("NOME");
} catch (JSONException e) {
// handle exception
}
}
Upvotes: 2