![](/img/trans.png)
[英]How to get nested JSON object and array from retrofit response on Android?
[英]How to get json object array from deep nested json array?
這是我的json,我想獲取“產品”數組對象。
{
"Categories":[
{
"id":6,
"status":"1",
"parent_id":"0",
"name":"Bottom Wear",
"name_ar":"\u0623\u0633\u0641\u0644 \u0627\u0631\u062a\u062f\u0627\u0621",
"picture":null,
"description":"gents bottom wear",
"slug":"bottom-wear",
"created_at":"2017-06-05 21:08:28",
"updated_at":"2017-06-05 21:08:28",
"deleted_at":null,
"product":[
{
"id":2,
"status":"1",
"name":"Pants",
"name_ar":"\u0628\u0646\u0637\u0644\u0648\u0646",
"dryclean_price":"9",
"washing_price":"6",
"press":"4",
"sw_dryclean_price":"9",
"sw_washing_price":"6",
"sw_press":"4",
"picture":null,
"created_at":"2017-04-19 21:32:04",
"updated_at":"2017-06-05 21:18:04",
"deleted_at":null,
"pivot":{
"category_id":"6",
"product_id":"2"
}
},
{
"id":8,
"status":"1",
"parent_id":"0",
"name":"Undergarments",
"name_ar":"\u0623\u062b\u0648\u0627\u0628 \u062a\u062d\u062a\u0627\u0646\u064a\u0629",
"picture":null,
"description":"Undergarments",
"slug":"undergarments",
"created_at":"2017-06-05 21:22:09",
"updated_at":"2017-06-05 21:22:09",
"deleted_at":null,
"product":[
{
"id":23,
"status":"1",
"name":"Underwear",
"name_ar":"\u062b\u064a\u0627\u0628 \u062f\u0627\u062e\u0644\u064a\u0629",
"dryclean_price":"5",
"washing_price":"3",
"press":"2",
"sw_dryclean_price":"5",
"sw_washing_price":"3",
"sw_press":"2",
"picture":null,
"created_at":"2017-04-19 21:35:31",
"updated_at":"2017-06-05 21:23:42",
"deleted_at":null,
"pivot":{
"category_id":"8",
"product_id":"23"
}
},
{
"id":34,
"status":"1",
"name":"Socks",
"name_ar":"\u062c\u0648\u0627\u0631\u0628",
"dryclean_price":"5",
"washing_price":"3",
"press":"2",
"sw_dryclean_price":"5",
"sw_washing_price":"3",
"sw_press":"2",
"picture":null,
"created_at":"2017-06-05 21:26:14",
"updated_at":"2017-06-05 21:26:14",
"deleted_at":null,
"pivot":{
"category_id":"8",
"product_id":"34"
}
}
]
}
]
}
]
}
我可以像這樣在我的數據庫中保存類別。
protected final String CategoryTable = "category_table";
protected final String D_ID = "category_id";
protected final String D_SERVER_ID = "categoryserver_id";
protected final String D_JSON = "category_json";
public boolean insertCategory(Category model) {
ContentValues cv = new ContentValues();
database = this.getWritableDatabase();
cv.put(D_SERVER_ID, model.getId());
cv.put(D_JSON, new Gson().toJson(model));
int res = (int) database.insert(CategoryTable, null, cv);
database.close();
if (res > 0) {
return true;
} else {
return false;
}
}
public Collection<Category> getAllCategories() {
database = this.getReadableDatabase();
Gson gson = new Gson();
ArrayList<Category> lst = new ArrayList<>();
Cursor c = database.rawQuery("SELECT * FROM " + CategoryTable, null);
if (c.moveToFirst()) {
do {
Category obj = gson.fromJson(c.getString(c.getColumnIndex(D_JSON)), Category.class);
if (obj != null)
lst.add(obj);
} while (c.moveToNext());
}
return lst;
}
這是一個類別模型類:
public class Category {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("status")
@Expose
private String status;
@SerializedName("parent_id")
@Expose
private String parentId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("name_ar")
@Expose
private String nameAr;
@SerializedName("description")
@Expose
private String description;
@SerializedName("slug")
@Expose
private String slug;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("deleted_at")
@Expose
private Object deletedAt;
@SerializedName("product")
@Expose
private List<Product> product = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNameAr() {
return nameAr;
}
public void setNameAr(String nameAr) {
this.nameAr = nameAr;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public Object getDeletedAt() {
return deletedAt;
}
public void setDeletedAt(Object deletedAt) {
this.deletedAt = deletedAt;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
我正在使用改造庫來獲取數據。 這是我用來將類別數組保存在數據庫中的方法。
@Override
public void onSuccess(Call call, Response response, int reqCode) {
Loading.cancel();
ProductsResponse productsResponse = (ProductsResponse) response.body();
for (int i = 0; i < productsResponse.getCategories().size(); i++) {
Category obj = productsResponse.getCategories().get(i);
categories.add(obj);
categoriesHandler.insertCategory(obj);
categoriesHandler.insertLabel(obj.getName());
}
adapter.notifyDataSetChanged();
loadSpinnerData();
}
但是如何從類別中獲取產品jsonArray。 嘗試了很多,但找不到方法。 您的幫助將不勝感激。 需要獲取基於類別的產品。 請幫助。 提前致謝。
Ashish我正在使用您的方法:
private void categorySelector(String str){
Gson gson = new GsonBuilder().create();
JSONArray mainData = (JSONArray) categoriesHandler.getAllCategories();
ArrayList<Category> responseAsArrayList =
gson.fromJson(mainData.toString(), new TypeToken<List<Category>>() {
}.getType());
for(int i =0;i<responseAsArrayList.size();i++)
{
for(int j = 0; j < responseAsArrayList.get(i).getProduct().size();j++)
{
Category category = responseAsArrayList.get(i);
Product product = category.getProduct().get(j);
products.add(product);
}
}
JSONArray array = object.optJSONArray("Categories"); // first get your Categories array from Json Object.
// Then iterate your categories array.
for (int i = 0; i <array.length ; i++)
{
JSONObject innerObject = array.getJSONObject(i); // get inner json object from array.
JSONArray innerArray = object.optJSONArray("product"); // then get product array from inner json object
}
1)如果創建和更新的是String,則也刪除一個字符串。
2)假設Person很好地反映了json結構,Pivot的類也是如此,要獲得產品,您可以執行以下操作:
ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
for(Product product : category.getProduct()){
<Do something with each product of the category >
}
}
3)在Category中,獲取產品列表的更好名稱是getPrduct s ()而不是getProduct()。
編輯1
要按產品名稱搜索:
緩慢的方式:
它遍歷所有類別,直到找到與productName匹配的產品。 如果有多個,則返回第一個。
Product getProductByName(String productName){
Product rtn = null;
ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
for(Product product : category.getProduct()){
if(product.getName().equals(productName){
rtn = product;
break;
}
}
}
return rtn;
}
您可以采用不同的方法來更快地進行搜索:
1)不用存儲json字符串,而是解包不同的對象並將信息放在不同的表中:categoris,products,pivot。
2)為每種產品建立某種索引,該索引記錄保留json字符串,類別ID和產品ID。 當您需要產品時,可以在索引中查找它並閱讀提取產品所需的特定記錄。
3)一種緩存策略,將慢速查找與hashmap
的索引結合在一起。
您可能還可以做更多的事情,這是為了提供一些想法。
編輯2
按類別名稱的產品:
ArrayList<Product> getProductsByCategoryName(String categoryName){
ArrayList<Product> rtn = new ArrayList<>();
ArrayList<Category> categories = getAllCategories();
for(Category category : categories){
if(category.getName().equals(categoryName){
rtn = category.getProduct();
}
}
return rtn;
}
第1步)使用gson屬性做出響應。http ://www.jsonschema2pojo.org/將有助於創建gson類。
youSource類型:JSON,批注樣式:GSON並添加getter setter方法。
第2步)現在,您有了所有帶有gson注釋的類。
步驟3)現在json
Gson gson = new GsonBuilder().create();
JSONArray mainData = response.getJSONArray("Categories");
ArrayList<YourMasterClass> responseAsArrayList =
gson.fromJson(mainData.toString(), new TypeToken<List<YourMasterClass>>() {
}.getType());
步驟4)現在將所有數據存儲在arraylist中后,您的邏輯就會起作用。
在這里,我只是假設使用arraylist名稱,因此請替換您的gson類。
for(int i =0;i<responseAsArrayList.size();i++)
{
for(int j = 0; responseAsArrayList.get(i).getProductArray().size();j++)
{
// Here you will get your Product object
}
}
json.getJSONArray(“ Categories”)。getJSONObject(0).getJSONArray(“ product”)
會給你產品陣列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.