[英]How to parse my json data in Android
我從HTTP收到此數據:
[
{
"ID": "1",
"NOME": "Nome 1",
"APELIDO": "Apelido 1",
"CATEGORIA": "1"
},
{
"ID": "2",
"NOME": "Nome 2",
"APELIDO": "Apelido 2",
"CATEGORIA": "1"
}
]
如何在Android ID = int
和CATEGORIA = int
上解析此數據?
你可以做
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
}
}
以防萬一,如果您要定義json,則可以將其更改為:[{“ ID”:1,“ NOME”:“ Nome 1”,“ APELIDO”:“ Apelido 1”,“ CATEGORIA”:1}, {“ ID”:2,“ NOME”:“ Nome 2”,“ APELIDO”:“ Apelido 2”,“ CATEGORIA”:1}]]
由於Json支持int類型,那么為什么要在String中采用這樣的值。 最好將它們直接帶入int。
要將ID和CATEGORIA轉換為整數,需要手動進行。 與json數據中的字符串一樣,您需要先將其放入字符串中,然后使用Integer.parseInt方法將其手動轉換為int。
我建議使用com.google.gson庫進行解析。 下面是您提到的Json的模型類(Data.java)。 您可以使用Data.parse(stringJson)獲取數據列表。
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;
}
}
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.