2016-07-01 2 views
2
{ 
"records": [ 
    { 
     "id": "744", 
     "categoryname": "Floor Tiles", 
     "photo": "", 
     "width": "0", 
     "height": "0", 
     "secondlevelcategory": [ 
      { 
       "id": "833", 
       "categoryname": "Digital Vitrified Tiles", 
       "photo": "http://image.com", 
       "width": "1031", 
       "height": "700" 
      } 
     ] 
    }, 
    { 
     "id": "744", 
     "categoryname": "Floor Tiles", 
     "photo": "", 
     "width": "0", 
     "height": "0", 
     "secondlevelcategory": [ 
      { 
       "id": "833", 
       "categoryname": "Digital Vitrified Tiles", 
       "photo": "http://image.com", 
       "width": "1031", 
       "height": "700" 
      } 
     ] 
    } 
] } 

Как я могу конвертировать этот ответ JSON дооснащения боба я получаю ошибку Gson как Использование JsonReader.setLenient (правда), чтобы принять искаженную JSON в строке 1 колонок 1 путь $Как получать JSON ответ с помощью Дооснащения

private void callCategoryApi() { 
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create(); 
    Retrofit retrofit = new Retrofit.Builder() 
      .baseUrl(GithubUserAPI.CATEGORY_API) 
      .addConverterFactory(GsonConverterFactory.create(gson)) 
      .build(); 

    GithubUserAPI githubUserAPI = retrofit.create(GithubUserAPI.class); 
    Call<List<CatResponseData>> call = githubUserAPI.getCategory(Utils.key); 
    call.enqueue(this); 

} 

@Override 
public void onResponse(Call<List<CatResponseData>> call, Response<List<CatResponseData>> response) { 
    int code = response.code(); 
    if (code == 200) { 
     List<CatResponseData> res = response.body(); 
     for(CatResponseData resDat : res){ 
      System.out.println("=== Response : " + resDat.getCategoryname()); 
     } 
    }else{ 
     Toast.makeText(this, "Did not work: " + String.valueOf(code), Toast.LENGTH_LONG).show(); 
    } 
} 

@Override 
public void onFailure(Call<List<CatResponseData>> call, Throwable t) { 
    System.out.println("=== Error : " + t.getMessage()); 
} 

и апи вызов

@POST("/apikey/{apikey}") 
Call<List<CatResponseData>> getCategory(@Path("apikey") String user); 

Строка CATEGORY_API = "https://api.callingservice.com";

пожалуйста, помогите мне решить эту проблему Как я могу конвертировать ответ JSON To Bean и мой класс Bean, как

public class CategoryBean { 
List<CatResponseData> responseData = new ArrayList<CatResponseData>(); } class CatResponseData { 
String id; 
public String getId() { 
    return id; 
} 
public void setId(String id) { 
    this.id = id; 
} 
public String getCategoryname() { 
    return categoryname; 
} 
public void setCategoryname(String categoryname) { 
    this.categoryname = categoryname; 
} 
String categoryname; } 

ответ

0

жаль, что я не могу комментировать, но я хочу, чтобы помочь; Не может быть, что retrofit ждет только для массива элементов без имени? Я имею в виду, может быть, вы должны сказать JSon, чтобы получить объект "записи", прежде чем итерация это

В моей модифицированной Im ПОЛУЧАТЬ JSon массив как: [{}, {}, {}]

вместо: {"records": [{}, {}, {}]}

1

Это должен быть класс, который вы предоставляете дооснащению. Не список компонентов, поскольку они инкапсулированы в объект.

public class CategoryResponse { 
    @SerializedName("records") 
    List<CategoryBean> responseData; 

    public List<CatResponseData> getResponseData() { 
      return responseData; 
    } 
} 
+0

Привет toshkinl Спасибо за респ onse, после создания класса CategoryResponse, то как я могу получить доступ к id, categoryname, height, secondlevelcategory и как я могу назвать api, пожалуйста, помогите мне, спасибо –

+0

Во-первых, так ваш bean-компонент должен выглядеть как http://pastebin.com/fqx3k1KH. Тогда, когда вы ставите в очередь вызов – toshkinl

+0

, да, отлично, я создаю bean-компонент как u show. –

0

Чтобы преобразовать, Gson нуждается в том же имени в полях класса. Я рекомендую использовать это site, вы можете вставить вас в JSON, и он возвращает класс в формате Gson.

Для каждого списка у вас есть класс с объектами. как:

Основной класс:

import java.util.ArrayList; 
    import java.util.List; 
    import javax.annotation.Generated; 
    import com.google.gson.annotations.Expose; 
    import com.google.gson.annotations.SerializedName; 

    @Generated("org.jsonschema2pojo") 
    public class Example { 

    @SerializedName("records") 
    @Expose 
    private List<Record> records = new ArrayList<Record>(); 

    /** 
    * No args constructor for use in serialization 
* 
*/ 
public Example() { 
} 

/** 
* 
* @param records 
*/ 
public Example(List<Record> records) { 
this.records = records; 
} 

/** 
* 
* @return 
* The records 
*/ 
public List<Record> getRecords() { 
return records; 
} 

/** 
* 
* @param records 
* The records 
*/ 
public void setRecords(List<Record> records) { 
this.records = records; 
} 

public Example withRecords(List<Record> records) { 
this.records = records; 
return this; 
} 

} 

Record.java

package com.example; 

import java.util.ArrayList; 
import java.util.List; 
import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

@Generated("org.jsonschema2pojo") 
public class Record { 

@SerializedName("id") 
@Expose 
private String id; 
@SerializedName("categoryname") 
@Expose 
private String categoryname; 
@SerializedName("photo") 
@Expose 
private String photo; 
@SerializedName("width") 
@Expose 
private String width; 
@SerializedName("height") 
@Expose 
private String height; 
@SerializedName("secondlevelcategory") 
@Expose 
private List<Secondlevelcategory> secondlevelcategory = new ArrayList<Secondlevelcategory>(); 

/** 
* No args constructor for use in serialization 
* 
*/ 
public Record() { 
} 

/** 
* 
* @param id 
* @param secondlevelcategory 
* @param height 
* @param width 
* @param categoryname 
* @param photo 
*/ 
public Record(String id, String categoryname, String photo, String width, String height, List<Secondlevelcategory> secondlevelcategory) { 
this.id = id; 
this.categoryname = categoryname; 
this.photo = photo; 
this.width = width; 
this.height = height; 
this.secondlevelcategory = secondlevelcategory; 
} 

/** 
* 
* @return 
* The id 
*/ 
public String getId() { 
return id; 
} 

/** 
* 
* @param id 
* The id 
*/ 
public void setId(String id) { 
this.id = id; 
} 

public Record withId(String id) { 
this.id = id; 
return this; 
} 

/** 
* 
* @return 
* The categoryname 
*/ 
public String getCategoryname() { 
return categoryname; 
} 

/** 
* 
* @param categoryname 
* The categoryname 
*/ 
public void setCategoryname(String categoryname) { 
this.categoryname = categoryname; 
} 

public Record withCategoryname(String categoryname) { 
this.categoryname = categoryname; 
return this; 
} 

/** 
* 
* @return 
* The photo 
*/ 
public String getPhoto() { 
return photo; 
} 

/** 
* 
* @param photo 
* The photo 
*/ 
public void setPhoto(String photo) { 
this.photo = photo; 
} 

public Record withPhoto(String photo) { 
this.photo = photo; 
return this; 
} 

/** 
* 
* @return 
* The width 
*/ 
public String getWidth() { 
return width; 
} 

/** 
* 
* @param width 
* The width 
*/ 
public void setWidth(String width) { 
this.width = width; 
} 

public Record withWidth(String width) { 
this.width = width; 
return this; 
} 

/** 
* 
* @return 
* The height 
*/ 
public String getHeight() { 
return height; 
} 

/** 
* 
* @param height 
* The height 
*/ 
public void setHeight(String height) { 
this.height = height; 
} 

public Record withHeight(String height) { 
this.height = height; 
return this; 
} 

/** 
* 
* @return 
* The secondlevelcategory 
*/ 
public List<Secondlevelcategory> getSecondlevelcategory() { 
return secondlevelcategory; 
} 

/** 
* 
* @param secondlevelcategory 
* The secondlevelcategory 
*/ 
public void setSecondlevelcategory(List<Secondlevelcategory> secondlevelcategory) { 
this.secondlevelcategory = secondlevelcategory; 
} 

public Record withSecondlevelcategory(List<Secondlevelcategory> secondlevelcategory) { 
this.secondlevelcategory = secondlevelcategory; 
return this; 
} 

} 

Secondlevelcategory.java

package com.example; 

import javax.annotation.Generated; 
import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

@Generated("org.jsonschema2pojo") 
public class Secondlevelcategory { 

@SerializedName("id") 
@Expose 
private String id; 
@SerializedName("categoryname") 
@Expose 
private String categoryname; 
@SerializedName("photo") 
@Expose 
private String photo; 
@SerializedName("width") 
@Expose 
private String width; 
@SerializedName("height") 
@Expose 
private String height; 

/** 
* No args constructor for use in serialization 
* 
*/ 
public Secondlevelcategory() { 
} 

/** 
* 
* @param id 
* @param height 
* @param width 
* @param categoryname 
* @param photo 
*/ 
public Secondlevelcategory(String id, String categoryname, String photo, String width, String height) { 
this.id = id; 
this.categoryname = categoryname; 
this.photo = photo; 
this.width = width; 
this.height = height; 
} 

/** 
* 
* @return 
* The id 
*/ 
public String getId() { 
return id; 
} 

/** 
* 
* @param id 
* The id 
*/ 
public void setId(String id) { 
this.id = id; 
} 

public Secondlevelcategory withId(String id) { 
this.id = id; 
return this; 
} 

/** 
* 
* @return 
* The categoryname 
*/ 
public String getCategoryname() { 
return categoryname; 
} 

/** 
* 
* @param categoryname 
* The categoryname 
*/ 
public void setCategoryname(String categoryname) { 
this.categoryname = categoryname; 
} 

public Secondlevelcategory withCategoryname(String categoryname) { 
this.categoryname = categoryname; 
return this; 
} 

/** 
* 
* @return 
* The photo 
*/ 
public String getPhoto() { 
return photo; 
} 

/** 
* 
* @param photo 
* The photo 
*/ 
public void setPhoto(String photo) { 
this.photo = photo; 
} 

public Secondlevelcategory withPhoto(String photo) { 
this.photo = photo; 
return this; 
} 

/** 
* 
* @return 
* The width 
*/ 
public String getWidth() { 
return width; 
} 

/** 
* 
* @param width 
* The width 
*/ 
public void setWidth(String width) { 
this.width = width; 
} 

public Secondlevelcategory withWidth(String width) { 
this.width = width; 
return this; 
} 

/** 
* 
* @return 
* The height 
*/ 
public String getHeight() { 
return height; 
} 

/** 
* 
* @param height 
* The height 
*/ 
public void setHeight(String height) { 
this.height = height; 
} 

public Secondlevelcategory withHeight(String height) { 
this.height = height; 
return this; 
} 

} 
+0

Привет, Лукас Спасибо за ответ, я просто создаю класс pojo по u, и я вызываю api как @POST ("/ apikey/{apikey} ") Звонок getCategory (@Path (" apikey ") Пользователь строки); можно сказать, где я делаю неправильно, потому что у меня есть все еще ошибка, как использовать JsonReader.setLenient (true), чтобы принять неверный JSON в строке 1 столбца 1 путь $ –

+0

на ваш onResponse, вы изменили класс правильно? Прежде чем это был список объектов, теперь это всего лишь один объект (со списком других объектов внутри него) –

Смежные вопросы