firstly i have trouble with creating database,then i want to put my received huge json datas(i converted json to java model by GsonBuilder and i saw all the datas in my entity[] list which made from ReceivedEntityModel class) to database,but i failed at first steps.it never creates my columns,so that after insertion there is 0 rowcount:(, i read all those answers about this topic and they didn't help me at all.I'm stuck.Anyone can help??
public void onCreate(SQLiteDatabase db)
{
String CREATE_M_ENTITY_TABLE = "CREATE TABLE " + TABLE_2_NAME + " ("
+ rId + " INTEGER PRIMARY KEY, "
+ ParentId + " INTEGER, "
+ Code+ " INTEGER, "
+ Label + " TEXT, "
+ LabelFL + " TEXT, "
+ EntityGroupId + " INTEGER, "
+ Property + " TEXT, "
+ ReportCode+ " INTEGER, "
+ Description + " TEXT, "
+ Code1Id + " INTEGER, "
+ Code2Id + " INTEGER, "
+ Code3Id + " INTEGER, "
+ Code4Id+ " INTEGER, "
+ Code5Id + " INTEGER, "
+ DefaultDimension1+ " INTEGER, "
+ DefaultDimension2 + "INTEGER, "
+ DefaultDimension3 + " INTEGER, "
+ CompanyId + " INTEGER, "
+ BranchId + " INTEGER, "
+ ReferenceDate + " TEXT, "
+ ResField1+ " TEXT, "
+ ResField2 + " TEXT, "
+ AreaId + " INTEGER, "
+ ModifiedDateTime + " TEXT, "
+ CreatedDateTime + " TEXT, "
+ RecId + " INTEGER, "
+ IsActive + " BIT,"
+ ModifiedBy + " INTEGER,"
+ CreatedBy + " INTEGER" + ") ";
db.execSQL(CREATE_M_ENTITY_TABLE);
}
i call this function at main activity to bind listview
public Cursor fetchEntities()
{
SQLiteDatabase db = dbHelper.getWritableDatabase();
String myQuery="Select Code, Label from entity";
Cursor mCursor=db.rawQuery(myQuery,null);
int rowCount=mCursor.getCount();
//Cursor mCursor = db.query(TABLE_2_NAME, new String[] {Code, Label }, null,null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//as you see there is paramater like ReceivedEntityModel ,i get the datas from this Model's getters and i want to put them into a database is shown below.
public void AddNewEntity(ReceivedEntityModel[] entity)
{
// addnewentity
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
for (int i = 0; i < entity.length; i++) {
values.put(rId, entity[i].getRId());
values.put(ParentId, entity[i].getParentId());
values.put(Code, entity[i].getCode());
values.put(Label, entity[i].getLabel());
values.put(LabelFL, entity[i].getLabelFL());
values.put(EntityGroupId, entity[i].getEntityGroupId());
values.put(ReportCode, entity[i].getReportCode());
values.put(Description, entity[i].getDescription());
values.put(Code1Id, entity[i].getCode1Id());
values.put(Code2Id, entity[i].getCode2Id());
values.put(Code3Id, entity[i].getCode3Id());
values.put(Code4Id, entity[i].getCode4Id());
values.put(Code5Id, entity[i].getCode5Id());
values.put(DefaultDimension1, entity[i].getDefaultDimension1Id());
values.put(DefaultDimension2, entity[i].getDefaultDimension2Id());
values.put(DefaultDimension3, entity[i].getDefaultDimension3Id());
values.put(CompanyId, entity[i].getCompanyId());
values.put(BranchId, entity[i].getBranchId());
values.put(ReferenceDate, entity[i].getReferenceDate());
values.put(ResField1, (String) entity[i].getResField1());
values.put(ResField2, (String) entity[i].getResField2());
values.put(AreaId, entity[i].getAreaId());
values.put(ModifiedDateTime, entity[i].getModifiedDateTime());
values.put(CreatedDateTime, entity[i].getCreatedDateTime());
values.put(RecId, entity[i].getRecId());
values.put(IsActive, entity[i].getIsActive());
values.put(ModifiedBy, entity[i].getModifiedBy());
values.put(CreatedBy, (String) entity[i].getCreatedBy());
}
db.insert(TABLE_2_NAME, null, values);
db.close();
}
this is Setup.java,fetchEntities(),AddNewEntity() functions are calling from there.Gson Builder make me a model.And the i call AddNewEntity()
protected String doInBackground(String... urls) {
entityReqestInfo = new EntityReqestInfo();
String cevap = POST_FOR_ENTITY(urls[0], entityReqestInfo);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
receivedEM = gson.fromJson(cevap, ReceivedEntityModel[].class);
myDB.getDatabaseEntityOperations().AddNewEntity(receivedEM);
pDialog.cancel();
return cevap;
}
and last of all my generated entity Model ReceivedEntityModel class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ReceivedEntityModel {
private Integer rId;
private Integer ParentId;
private String Code;
private String Label;
private String LabelFL;
private Integer EntityGroupId;
private String Property;
private String ReportCode;
private String Description;
private Integer Code1Id;
private Integer Code2Id;
private Integer Code3Id;
private Integer Code4Id;
private Integer Code5Id;
private Integer DefaultDimension1Id;
private Integer DefaultDimension2Id;
private Integer DefaultDimension3Id;
private Integer CompanyId;
private Integer BranchId;
private String ReferenceDate;
private String ResField1;
private String ResField2;
private String AreaId;
private String ModifiedDateTime;
private String CreatedDateTime;
private Integer RecId;
private Boolean IsActive;
private Integer ModifiedBy;
private String CreatedBy;
private String DBranch;
private String DCompany;
private String MEntityGroup;
private List<String> MEntityTableModule = new ArrayList<String>();
private Map<String, String> additionalProperties = new HashMap<String, String>();
/**
*
* #return The rId
*/
public Integer getRId() {
return rId;
}
/**
*
* #param rId
* The rId
*/
public void setRId(Integer rId) {
this.rId = rId;
}
public ReceivedEntityModel withRId(Integer rId) {
this.rId = rId;
return this;
}
/**
*
* #return The ParentId
*/
public Integer getParentId() {
return ParentId;
}
/**
*
* #param ParentId
* The ParentId
*/
public void setParentId(Integer ParentId) {
this.ParentId = ParentId;
}
public ReceivedEntityModel withParentId(Integer ParentId) {
this.ParentId = ParentId;
return this;
}
/**
*
* #return The Code
*/
public String getCode() {
return Code;
}
/**
*
* #param Code
* The Code
*/
public void setCode(String Code) {
this.Code = Code;
}
public ReceivedEntityModel withCode(String Code) {
this.Code = Code;
return this;
}
/**
*
* #return The Label
*/
public String getLabel() {
return Label;
}
/**
*
* #param Label
* The Label
*/
public void setLabel(String Label) {
this.Label = Label;
}
public ReceivedEntityModel withLabel(String Label) {
this.Label = Label;
return this;
}
/**
*
* #return The LabelFL
*/
public String getLabelFL() {
return LabelFL;
}
/**
*
* #param LabelFL
* The LabelFL
*/
public void setLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
}
public ReceivedEntityModel withLabelFL(String LabelFL) {
this.LabelFL = LabelFL;
return this;
}
/**
*
* #return The EntityGroupId
*/
public Integer getEntityGroupId() {
return EntityGroupId;
}
/**
*
* #param EntityGroupId
* The EntityGroupId
*/
public void setEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
}
public ReceivedEntityModel withEntityGroupId(Integer EntityGroupId) {
this.EntityGroupId = EntityGroupId;
return this;
}
/**
*
* #return The Property
*/
public String getProperty() {
return Property;
}
/**
*
* #param Property
* The Property
*/
public void setProperty(String Property) {
this.Property = Property;
}
public ReceivedEntityModel withProperty(String Property) {
this.Property = Property;
return this;
}
/**
*
* #return The ReportCode
*/
public String getReportCode() {
return ReportCode;
}
/**
*
* #param ReportCode
* The ReportCode
*/
public void setReportCode(String ReportCode) {
this.ReportCode = ReportCode;
}
public ReceivedEntityModel withReportCode(String ReportCode) {
this.ReportCode = ReportCode;
return this;
}
/**
*
* #return The Description
*/
public String getDescription() {
return Description;
}
/**
*
* #param Description
* The Description
*/
public void setDescription(String Description) {
this.Description = Description;
}
public ReceivedEntityModel withDescription(String Description) {
this.Description = Description;
return this;
}
/**
*
* #return The Code1Id
*/
public Integer getCode1Id() {
return Code1Id;
}
/**
*
* #param Code1Id
* The Code1Id
*/
public void setCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
}
public ReceivedEntityModel withCode1Id(Integer Code1Id) {
this.Code1Id = Code1Id;
return this;
}
/**
*
* #return The Code2Id
*/
public Integer getCode2Id() {
return Code2Id;
}
/**
*
* #param Code2Id
* The Code2Id
*/
public void setCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
}
public ReceivedEntityModel withCode2Id(Integer Code2Id) {
this.Code2Id = Code2Id;
return this;
}
/**
*
* #return The Code3Id
*/
public Integer getCode3Id() {
return Code3Id;
}
/**
*
* #param Code3Id
* The Code3Id
*/
public void setCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
}
public ReceivedEntityModel withCode3Id(Integer Code3Id) {
this.Code3Id = Code3Id;
return this;
}
/**
*
* #return The Code4Id
*/
public Integer getCode4Id() {
return Code4Id;
}
/**
*
* #param Code4Id
* The Code4Id
*/
public void setCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
}
public ReceivedEntityModel withCode4Id(Integer Code4Id) {
this.Code4Id = Code4Id;
return this;
}
/**
*
* #return The Code5Id
*/
public Integer getCode5Id() {
return Code5Id;
}
/**
*
* #param Code5Id
* The Code5Id
*/
public void setCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
}
public ReceivedEntityModel withCode5Id(Integer Code5Id) {
this.Code5Id = Code5Id;
return this;
}
/**
*
* #return The DefaultDimension1Id
*/
public Integer getDefaultDimension1Id() {
return DefaultDimension1Id;
}
/**
*
* #param DefaultDimension1Id
* The DefaultDimension1Id
*/
public void setDefaultDimension1Id(Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
}
public ReceivedEntityModel withDefaultDimension1Id(
Integer DefaultDimension1Id) {
this.DefaultDimension1Id = DefaultDimension1Id;
return this;
}
/**
*
* #return The DefaultDimension2Id
*/
public Integer getDefaultDimension2Id() {
return DefaultDimension2Id;
}
/**
*
* #param DefaultDimension2Id
* The DefaultDimension2Id
*/
public void setDefaultDimension2Id(Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
}
public ReceivedEntityModel withDefaultDimension2Id(
Integer DefaultDimension2Id) {
this.DefaultDimension2Id = DefaultDimension2Id;
return this;
}
/**
*
* #return The DefaultDimension3Id
*/
public Integer getDefaultDimension3Id() {
return DefaultDimension3Id;
}
/**
*
* #param DefaultDimension3Id
* The DefaultDimension3Id
*/
public void setDefaultDimension3Id(Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
}
public ReceivedEntityModel withDefaultDimension3Id(
Integer DefaultDimension3Id) {
this.DefaultDimension3Id = DefaultDimension3Id;
return this;
}
/**
*
* #return The CompanyId
*/
public Integer getCompanyId() {
return CompanyId;
}
/**
*
* #param CompanyId
* The CompanyId
*/
public void setCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
}
public ReceivedEntityModel withCompanyId(Integer CompanyId) {
this.CompanyId = CompanyId;
return this;
}
/**
*
* #return The BranchId
*/
public Integer getBranchId() {
return BranchId;
}
/**
*
* #param BranchId
* The BranchId
*/
public void setBranchId(Integer BranchId) {
this.BranchId = BranchId;
}
public ReceivedEntityModel withBranchId(Integer BranchId) {
this.BranchId = BranchId;
return this;
}
/**
*
* #return The ReferenceDate
*/
public String getReferenceDate() {
return ReferenceDate;
}
/**
*
* #param ReferenceDate
* The ReferenceDate
*/
public void setReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
}
public ReceivedEntityModel withReferenceDate(String ReferenceDate) {
this.ReferenceDate = ReferenceDate;
return this;
}
/**
*
* #return The ResField1
*/
public String getResField1() {
return ResField1;
}
/**
*
* #param ResField1
* The ResField1
*/
public void setResField1(String ResField1) {
this.ResField1 = ResField1;
}
public ReceivedEntityModel withResField1(String ResField1) {
this.ResField1 = ResField1;
return this;
}
/**
*
* #return The ResField2
*/
public String getResField2() {
return ResField2;
}
/**
*
* #param ResField2
* The ResField2
*/
public void setResField2(String ResField2) {
this.ResField2 = ResField2;
}
public ReceivedEntityModel withResField2(String ResField2) {
this.ResField2 = ResField2;
return this;
}
/**
*
* #return The AreaId
*/
public String getAreaId() {
return AreaId;
}
/**
*
* #param AreaId
* The AreaId
*/
public void setAreaId(String AreaId) {
this.AreaId = AreaId;
}
public ReceivedEntityModel withAreaId(String AreaId) {
this.AreaId = AreaId;
return this;
}
/**
*
* #return The ModifiedDateTime
*/
public String getModifiedDateTime() {
return ModifiedDateTime;
}
/**
*
* #param ModifiedDateTime
* The ModifiedDateTime
*/
public void setModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
}
public ReceivedEntityModel withModifiedDateTime(String ModifiedDateTime) {
this.ModifiedDateTime = ModifiedDateTime;
return this;
}
/**
*
* #return The CreatedDateTime
*/
public String getCreatedDateTime() {
return CreatedDateTime;
}
/**
*
* #param CreatedDateTime
* The CreatedDateTime
*/
public void setCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
}
public ReceivedEntityModel withCreatedDateTime(String CreatedDateTime) {
this.CreatedDateTime = CreatedDateTime;
return this;
}
/**
*
* #return The RecId
*/
public Integer getRecId() {
return RecId;
}
/**
*
* #param RecId
* The RecId
*/
public void setRecId(Integer RecId) {
this.RecId = RecId;
}
public ReceivedEntityModel withRecId(Integer RecId) {
this.RecId = RecId;
return this;
}
/**
*
* #return The IsActive
*/
public Boolean getIsActive() {
return IsActive;
}
/**
*
* #param IsActive
* The IsActive
*/
public void setIsActive(Boolean IsActive) {
this.IsActive = IsActive;
}
public ReceivedEntityModel withIsActive(Boolean IsActive) {
this.IsActive = IsActive;
return this;
}
/**
*
* #return The ModifiedBy
*/
public Integer getModifiedBy() {
return ModifiedBy;
}
/**
*
* #param ModifiedBy
* The ModifiedBy
*/
public void setModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
}
public ReceivedEntityModel withModifiedBy(Integer ModifiedBy) {
this.ModifiedBy = ModifiedBy;
return this;
}
/**
*
* #return The CreatedBy
*/
public String getCreatedBy() {
return CreatedBy;
}
/**
*
* #param CreatedBy
* The CreatedBy
*/
public void setCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
}
public ReceivedEntityModel withCreatedBy(String CreatedBy) {
this.CreatedBy = CreatedBy;
return this;
}
/**
*
* #return The DBranch
*/
public String getDBranch() {
return DBranch;
}
/**
*
* #param DBranch
* The D_Branch
*/
public void setDBranch(String DBranch) {
this.DBranch = DBranch;
}
public ReceivedEntityModel withDBranch(String DBranch) {
this.DBranch = DBranch;
return this;
}
/**
*
* #return The DCompany
*/
public String getDCompany() {
return DCompany;
}
/**
*
* #param DCompany
* The D_Company
*/
public void setDCompany(String DCompany) {
this.DCompany = DCompany;
}
public ReceivedEntityModel withDCompany(String DCompany) {
this.DCompany = DCompany;
return this;
}
/**
*
* #return The MEntityGroup
*/
public String getMEntityGroup() {
return MEntityGroup;
}
/**
*
* #param MEntityGroup
* The M_EntityGroup
*/
public void setMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
}
public ReceivedEntityModel withMEntityGroup(String MEntityGroup) {
this.MEntityGroup = MEntityGroup;
return this;
}
/**
*
* #return The MEntityTableModule
*/
public List<String> getMEntityTableModule() {
return MEntityTableModule;
}
/**
*
* #param MEntityTableModule
* The M_EntityTableModule
*/
public void setMEntityTableModule(List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
}
public ReceivedEntityModel withMEntityTableModule(
List<String> MEntityTableModule) {
this.MEntityTableModule = MEntityTableModule;
return this;
}
public Map<String, String> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
}
public ReceivedEntityModel withAdditionalProperty(String name, String value) {
this.additionalProperties.put(name, value);
return this;
}
}
Where are the column names defined?
The DefaultDimension2 column is not created with the intended name
in your table, because you forgot a space here:
+ DefaultDimension2 + "INTEGER, "
It must be
+ DefaultDimension2 + " INTEGER, "
So, supposing that the DefaultDimension2 column name is defined as
public String DefaultDimension2 = "DefaultDimension2";
it is actually created as "DefaultDimension2INTEGER, " instead of "DefaultDimension2 INTEGER, "
It's really a common mistake, mostly due to hurry.
Related
I'm getting a problem with the return value after the post request, the response string contains the requested JSON text but the dataBean is null ??
#Override
public wDataBean doInBackground(Void... params) {
wDataBean dataBean = new wDataBean();
try {
Response response = client.newCall(request).execute();
String responseString = response.body().string();
JSONObject jsonObject = new JSONObject(responseString);
Gson gson = new Gson();
dataBean = gson.fromJson(jsonObject.toString(), wDataBean.class);
}
catch (final IOException e)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
return dataBean;
}
This is a sample of the response:
{ "IsOK":true,
"Response":"Logged in successfully",
"MyArray":{ "user":"35",
"email":"email#domain.com",
"img":"https:\/\/www.mywebsite.com\/uploads\/136_image.png",
"fname":"First Name",
"lname":"Last Name",
"myToken":
{
"auth":"xyzxyzyxyzxyzxyzxyzxyzxyzxyzxyzxyzxyz",
"expiry":"1980-01-01 00:00:00"
}
},
"myToken":{}
}
wDataBean.java
public class wDataBean {
private Main1 main;
public Main1 getMain() {return main;}
public void setMain(Main1 main) {this.main = main;}
class Main1 {
boolean IsOK;
String Response;
JSONArray MyArray;
int user;
String email;
String img;
String fname;
String lname;
JSONArray myToken;
String auth;
Date expiry;
public boolean isOK() {return isOK();}
public int getUser() {return user;}
public JSONArray getMyArray() {return MyArray;}
public String getEmail() {return email;}
public String getImg() {return img;}
public String getResponse() {return Response;}
public Date getExpiry() {return expiry;}
public JSONArray getMyToken() {return myToken;}
public String getAuth() {return auth;}
public String getFname() {return fname;}
public String getLname() {return lname;}
public void setAuth(String auth) {this.auth = auth;}
public void setEmail(String email) {this.email = email;}
public void setExpiry(Date expiry) {this.expiry = expiry;}
public void setFname(String fname) {this.fname = fname;}
public void setImg(String img) {this.img = img;}
public void setLname(String lname) {this.lname = lname;}
public void setMyArray(JSONArray myArray) {MyArray = myArray;}
public void setMyToken(JSONArray myToken) {this.myToken = myToken;}
public void setOK(boolean OK) {IsOK = OK;}
public void setResponse(String response) { Response = response;}
public void setUser(int user) { this.user = user;}
}
}
The goal is to get "auth" and "expiry" from myToken
This should be your bean class -
public class WDataBean {
#SerializedName("IsOK")
#Expose
private Boolean isOK;
#SerializedName("Response")
#Expose
private String response;
#SerializedName("MyArray")
#Expose
private MyArray myArray;
#SerializedName("myToken")
#Expose
private MyToken_ myToken;
/**
*
* #return
* The isOK
*/
public Boolean getIsOK() {
return isOK;
}
/**
*
* #param isOK
* The IsOK
*/
public void setIsOK(Boolean isOK) {
this.isOK = isOK;
}
/**
*
* #return
* The response
*/
public String getResponse() {
return response;
}
/**
*
* #param response
* The Response
*/
public void setResponse(String response) {
this.response = response;
}
/**
*
* #return
* The myArray
*/
public MyArray getMyArray() {
return myArray;
}
/**
*
* #param myArray
* The MyArray
*/
public void setMyArray(MyArray myArray) {
this.myArray = myArray;
}
/**
*
* #return
* The myToken
*/
public MyToken_ getMyToken() {
return myToken;
}
/**
*
* #param myToken
* The myToken
*/
public void setMyToken(MyToken_ myToken) {
this.myToken = myToken;
}
public class MyToken_ {
}
public class MyToken {
#SerializedName("auth")
#Expose
private String auth;
#SerializedName("expiry")
#Expose
private String expiry;
/**
*
* #return
* The auth
*/
public String getAuth() {
return auth;
}
/**
*
* #param auth
* The auth
*/
public void setAuth(String auth) {
this.auth = auth;
}
/**
*
* #return
* The expiry
*/
public String getExpiry() {
return expiry;
}
/**
*
* #param expiry
* The expiry
*/
public void setExpiry(String expiry) {
this.expiry = expiry;
}
}
public class MyArray {
#SerializedName("user")
#Expose
private String user;
#SerializedName("email")
#Expose
private String email;
#SerializedName("img")
#Expose
private String img;
#SerializedName("fname")
#Expose
private String fname;
#SerializedName("lname")
#Expose
private String lname;
#SerializedName("myToken")
#Expose
private MyToken myToken;
/**
*
* #return
* The user
*/
public String getUser() {
return user;
}
/**
*
* #param user
* The user
*/
public void setUser(String user) {
this.user = user;
}
/**
*
* #return
* The email
*/
public String getEmail() {
return email;
}
/**
*
* #param email
* The email
*/
public void setEmail(String email) {
this.email = email;
}
/**
*
* #return
* The img
*/
public String getImg() {
return img;
}
/**
*
* #param img
* The img
*/
public void setImg(String img) {
this.img = img;
}
/**
*
* #return
* The fname
*/
public String getFname() {
return fname;
}
/**
*
* #param fname
* The fname
*/
public void setFname(String fname) {
this.fname = fname;
}
/**
*
* #return
* The lname
*/
public String getLname() {
return lname;
}
/**
*
* #param lname
* The lname
*/
public void setLname(String lname) {
this.lname = lname;
}
/**
*
* #return
* The myToken
*/
public MyToken getMyToken() {
return myToken;
}
/**
*
* #param myToken
* The myToken
*/
public void setMyToken(MyToken myToken) {
this.myToken = myToken;
}
}
}
Can you show me the class wDataBean?
But I venture to say that this can solve
Gson gson = new GsonBuilder().setDateFormat("yyyy-mm-dd HH:mm:ss").create();
I have a collection of document inside another document. Would like to implement pagination on nested element while fetching the data. Could you please let me know how to do that? In the structure I would like to fetch messages using pagination.
public abstract class CommonDomainAttributes implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
#Id
protected String id;
#JsonIgnore
#CreatedDate
protected Date createDate;
//#JsonIgnore
#LastModifiedDate
//#JsonSerialize(using=JsonDateSerializer.class)
protected Date lastModifiedDate;
#JsonIgnore
#CreatedBy
protected String createdBy;
#JsonIgnore
#LastModifiedBy
protected String lastModifiedBy;
/**
* #return the id
*/
public String getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* #return the createDate
*/
public Date getCreateDate() {
return createDate;
}
/**
* #param createDate the createDate to set
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* #return the lastModifiedDate
*/
public Date getLastModifiedDate() {
return lastModifiedDate;
}
/**
* #param lastModifiedDate the lastModifiedDate to set
*/
public void setLastModifiedDate(Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
/**
* #return the createdBy
*/
public String getCreatedBy() {
return createdBy;
}
/**
* #param createdBy the createdBy to set
*/
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
/**
* #return the lastModifiedBy
*/
public String getLastModifiedBy() {
return lastModifiedBy;
}
/**
* #param lastModifiedBy the lastModifiedBy to set
*/
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
/* (non-Javadoc)
* #see java.lang.Object#hashCode()
*/
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (id == null ? 0 : id.hashCode());
return result;
}
/* (non-Javadoc)
* #see java.lang.Object#equals(java.lang.Object)
*/
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
CommonDomainAttributes other = (CommonDomainAttributes) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CommonDomainAttributes [id=").append(id)
.append(", createDate=").append(createDate)
.append(", lastModifiedDate=").append(lastModifiedDate)
.append(", createdBy=").append(createdBy)
.append(", lastModifiedBy=").append(lastModifiedBy)
.append(", toString()=").append(super.toString()).append("]");
return builder.toString();
}
}
public class Message extends CommonDomainAttributes implements Serializable{
private String fromuserId;
private String fromuserName;
private String toUserId;
private String touserName;
private String message;
/**
* #return the fromuserId
*/
public String getFromuserId() {
return fromuserId;
}
/**
* #param fromuserId the fromuserId to set
*/
public void setFromuserId(String fromuserId) {
this.fromuserId = fromuserId;
}
/**
* #return the fromuserName
*/
public String getFromuserName() {
return fromuserName;
}
/**
* #param fromuserName the fromuserName to set
*/
public void setFromuserName(String fromuserName) {
this.fromuserName = fromuserName;
}
/**
* #return the toUserId
*/
public String getToUserId() {
return toUserId;
}
/**
* #param toUserId the toUserId to set
*/
public void setToUserId(String toUserId) {
this.toUserId = toUserId;
}
/**
* #return the touserName
*/
public String getTouserName() {
return touserName;
}
/**
* #param touserName the touserName to set
*/
public void setTouserName(String touserName) {
this.touserName = touserName;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Message [fromuserId=");
builder.append(fromuserId);
builder.append(", fromuserName=");
builder.append(fromuserName);
builder.append(", toUserId=");
builder.append(toUserId);
builder.append(", touserName=");
builder.append(touserName);
builder.append(", message=");
builder.append(message);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
#Document(collection="discussion")
#TypeAlias("discussion")
public class Discussion extends CommonDomainAttributes implements Serializable{
private String discussionTopic;
private List<Message> messages;
/**
* #return the discussionTopic
*/
public String getDiscussionTopic() {
return discussionTopic;
}
/**
* #param discussionTopic the discussionTopic to set
*/
public void setDiscussionTopic(String discussionTopic) {
this.discussionTopic = discussionTopic;
}
/**
* #return the messages
*/
public List<Message> getMessages() {
return messages;
}
/**
* #param messages the messages to set
*/
public void setMessages(List<Message> messages) {
this.messages = messages;
}
/**
* #param messages the messages to set
*/
public void addMessages(Message message) {
if(null == messages){
messages = new LinkedList<>();
}
messages.add(message);
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Discussion [discussionTopic=");
builder.append(discussionTopic);
builder.append(", messages=");
builder.append(messages);
builder.append(", toString()=");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
A bit on Mongo Query Language
In MongoDB, the $slice operator controls the number of items of an array that a query returns. The $slice operator can accept values with following syntax:
[toSkip, toLimit]
Where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return. For example, you can use the following query:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
To return 10 messages, after skipping the first 20 messages of that array.
Bring it to Spring Data World
In order to use $slice operator with Spring Data MongoDB, you should use #Query annotation and its fields attribute. For example, if you have a DiscussionRepository, you could write something like:
public interface DiscussionRepository extends MongoRepository<Discussion, String> {
#Query(value = "{}", fields = "{messages: {$slice: [?0, ?1]}}")
List<Discussion> findDiscussions(int skip, int limit);
}
With this arrangement, following method call:
discussionRepository.findDiscussions(20, 10)
Would generate the same result as:
db.discussions.find({}, {messages: {$slice: [20, 10]}})
With a little bit of work, you can turn the Skip/Limit combination to a pagination functionality.
I am passing a json array from activity A to activity B.Then I am using the GSON library to insert a value into the array.This is my current code.
public void gsonResponse(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++) {
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();
JSONObject innerJosonObject = new JSONObject(jsonArray.getString(i));
// you need to put all values from jsonObject to map for managing the order..
linkedHashMap.put("doc_no", textViewInvNo.getText().toString());
linkedHashMap.put("itembarcode", innerJosonObject.getString("itembarcode"));
linkedHashMap.put("net_wt", innerJosonObject.getString("net_wt"));
linkedHashMap.put("gross_wt", innerJosonObject.getString("gross_wt"));
linkedHashMap.put("stone_wt", innerJosonObject.getString("stone_wt"));
linkedHashMap.put("stone_amt", innerJosonObject.getString("stone_amt"));
linkedHashMap.put("rate", innerJosonObject.getString("rate"));
linkedHashMap.put("making", innerJosonObject.getString("making"));
linkedHashMap.put("qty", innerJosonObject.getString("qty"));
linkedHashMap.put("net_rate", innerJosonObject.getString("net_rate"));
linkedHashMap.put("item_total", innerJosonObject.getString("item_total"));
linkedHashMap.put("sum_total", innerJosonObject.getString("sum_total"));
Gson gson = new Gson();
// convert linkedHashMap to json string and it will keep the insertion order..
String string = gson.toJson(linkedHashMap, LinkedHashMap.class);
jsonArray.put(i, string);
}
jsonObject.put("result", jsonArray);
String jsonResp = jsonObject.toString();
jsonFormattedString = jsonResp.replaceAll("\\\\","");
Log.d("NEW JSON", jsonFormattedString);
} catch (JSONException e) {
e.printStackTrace();
}
}
The output for this is :-
{"result":["{"doc_no":"ES101","itembarcode":"BRMS","net_wt":"10","gross_wt":"1","stone_wt":"0","stone_amt":"0","rate":"32000","making":"100","qty":"1","net_rate":"32100.0","item_total":"32100.0","sum_total":"64600.0"}",
"{"doc_no":"ES101","itembarcode":"MSAA0015","net_wt":"10","gross_wt":"11","stone_wt":"100000","stone_amt":"1","rate":"32000","making":"500","qty":"1","net_rate":"32500.0","item_total":"32500.0","sum_total":"64600.0"}"]}
But my desired output should be something like :-
[{"doc_no":"IN1001","itembarcode":"BRMS123456\nFLT22K","net_wt":"10","gross_wt":"10","stone_amt":"0","rate":"29000","making":"999","qty":"1","net_rate":"29999.0","item_total":"29999.0","sum_total":"30299.0","stone_wt":"0"},
{"doc_no":"IN1001","itembarcode":"BRMS\nGA24K","net_wt":"10","gross_wt":"1","stone_amt":"0","rate":"32000","making":"100","qty":"1","net_rate":"","item_total":"","sum_total":"30299.0","stone_wt":""}]
How can I achieve it? Any suggestion or help is appreciated.Thank You.
Actually you don't need the following line:
jsonObject.put("result", jsonArray);
Just use the existing jsonArray like the following:
String jsonResp = jsonArray.toString();
One other note. you will get extra " " in your response and that is because of jsonArray.put(i, string); statement in the for loop which inserts extra " ". you can simply use the following to fix that:
jsonResp = jsonResp.replaceAll("\"[{]", "{");
jsonResp = jsonResp.replaceAll("[}]\"", "}");
Make a Model like This DocInfoModel.java ->
public class DocInfoModel {
#SerializedName("doc_no")
#Expose
private String docNo;
#SerializedName("itembarcode")
#Expose
private String itembarcode;
#SerializedName("net_wt")
#Expose
private String netWt;
#SerializedName("gross_wt")
#Expose
private String grossWt;
#SerializedName("stone_amt")
#Expose
private String stoneAmt;
#SerializedName("rate")
#Expose
private String rate;
#SerializedName("making")
#Expose
private String making;
#SerializedName("qty")
#Expose
private String qty;
#SerializedName("net_rate")
#Expose
private String netRate;
#SerializedName("item_total")
#Expose
private String itemTotal;
#SerializedName("sum_total")
#Expose
private String sumTotal;
#SerializedName("stone_wt")
#Expose
private String stoneWt;
/**
*
* #return
* The docNo
*/
public String getDocNo() {
return docNo;
}
/**
*
* #param docNo
* The doc_no
*/
public void setDocNo(String docNo) {
this.docNo = docNo;
}
/**
*
* #return
* The itembarcode
*/
public String getItembarcode() {
return itembarcode;
}
/**
*
* #param itembarcode
* The itembarcode
*/
public void setItembarcode(String itembarcode) {
this.itembarcode = itembarcode;
}
/**
*
* #return
* The netWt
*/
public String getNetWt() {
return netWt;
}
/**
*
* #param netWt
* The net_wt
*/
public void setNetWt(String netWt) {
this.netWt = netWt;
}
/**
*
* #return
* The grossWt
*/
public String getGrossWt() {
return grossWt;
}
/**
*
* #param grossWt
* The gross_wt
*/
public void setGrossWt(String grossWt) {
this.grossWt = grossWt;
}
/**
*
* #return
* The stoneAmt
*/
public String getStoneAmt() {
return stoneAmt;
}
/**
*
* #param stoneAmt
* The stone_amt
*/
public void setStoneAmt(String stoneAmt) {
this.stoneAmt = stoneAmt;
}
/**
*
* #return
* The rate
*/
public String getRate() {
return rate;
}
/**
*
* #param rate
* The rate
*/
public void setRate(String rate) {
this.rate = rate;
}
/**
*
* #return
* The making
*/
public String getMaking() {
return making;
}
/**
*
* #param making
* The making
*/
public void setMaking(String making) {
this.making = making;
}
/**
*
* #return
* The qty
*/
public String getQty() {
return qty;
}
/**
*
* #param qty
* The qty
*/
public void setQty(String qty) {
this.qty = qty;
}
/**
*
* #return
* The netRate
*/
public String getNetRate() {
return netRate;
}
/**
*
* #param netRate
* The net_rate
*/
public void setNetRate(String netRate) {
this.netRate = netRate;
}
/**
*
* #return
* The itemTotal
*/
public String getItemTotal() {
return itemTotal;
}
/**
*
* #param itemTotal
* The item_total
*/
public void setItemTotal(String itemTotal) {
this.itemTotal = itemTotal;
}
/**
*
* #return
* The sumTotal
*/
public String getSumTotal() {
return sumTotal;
}
/**
*
* #param sumTotal
* The sum_total
*/
public void setSumTotal(String sumTotal) {
this.sumTotal = sumTotal;
}
/**
*
* #return
* The stoneWt
*/
public String getStoneWt() {
return stoneWt;
}
/**
*
* #param stoneWt
* The stone_wt
*/
public void setStoneWt(String stoneWt) {
this.stoneWt = stoneWt;
}
}
And Parse the json by GSON ->
Gson gson = new Gson();
DocInfoModel[] docModel = gson.fromJson(RESPONSE_STRING,DocInfoModel[].class);
I would suggest to create Model class for your GSON implementation.
Check out this solution.
private void testDoc()
{
String json = "{\"result\":[{\"doc_no\":\"ES101\",\"itembarcode\":\"BRMS\",\"net_wt\":\"10\",\"gross_wt\":\"1\",\"stone_wt\":\"0\",\"stone_amt\":\"0\",\"rate\":\"32000\",\"making\":\"100\",\"qty\":\"1\",\"net_rate\":\"32100.0\",\"item_total\":\"32100.0\",\"sum_total\":\"64600.0\"},{\"doc_no\":\"ES101\",\"itembarcode\":\"MSAA0015\",\"net_wt\":\"10\",\"gross_wt\":\"11\",\"stone_wt\":\"100000\",\"stone_amt\":\"1\",\"rate\":\"32000\",\"making\":\"500\",\"qty\":\"1\",\"net_rate\":\"32500.0\",\"item_total\":\"32500.0\",\"sum_total\":\"64600.0\"}]}";
Gson gson = new Gson();
DocInfo docInfo = gson.fromJson(json, DocInfo.class);
System.out.println("Before ***********************");
System.out.println(gson.toJson(docInfo));
for(Result result : docInfo.getResult())
{
result.setDocNo("New Doc No");
}
System.out.println("After ***********************");
System.out.println(gson.toJson(docInfo));
}
DocInfo.java
import java.util.ArrayList;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class DocInfo {
#SerializedName("result")
#Expose
private List<Result> result = new ArrayList<Result>();
/**
*
* #return
* The result
*/
public List<Result> getResult() {
return result;
}
/**
*
* #param result
* The result
*/
public void setResult(List<Result> result) {
this.result = result;
}
}
Result.java
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Result {
#SerializedName("doc_no")
#Expose
private String docNo;
#SerializedName("itembarcode")
#Expose
private String itembarcode;
#SerializedName("net_wt")
#Expose
private String netWt;
#SerializedName("gross_wt")
#Expose
private String grossWt;
#SerializedName("stone_wt")
#Expose
private String stoneWt;
#SerializedName("stone_amt")
#Expose
private String stoneAmt;
#SerializedName("rate")
#Expose
private String rate;
#SerializedName("making")
#Expose
private String making;
#SerializedName("qty")
#Expose
private String qty;
#SerializedName("net_rate")
#Expose
private String netRate;
#SerializedName("item_total")
#Expose
private String itemTotal;
#SerializedName("sum_total")
#Expose
private String sumTotal;
/**
*
* #return
* The docNo
*/
public String getDocNo() {
return docNo;
}
/**
*
* #param docNo
* The doc_no
*/
public void setDocNo(String docNo) {
this.docNo = docNo;
}
/**
*
* #return
* The itembarcode
*/
public String getItembarcode() {
return itembarcode;
}
/**
*
* #param itembarcode
* The itembarcode
*/
public void setItembarcode(String itembarcode) {
this.itembarcode = itembarcode;
}
/**
*
* #return
* The netWt
*/
public String getNetWt() {
return netWt;
}
/**
*
* #param netWt
* The net_wt
*/
public void setNetWt(String netWt) {
this.netWt = netWt;
}
/**
*
* #return
* The grossWt
*/
public String getGrossWt() {
return grossWt;
}
/**
*
* #param grossWt
* The gross_wt
*/
public void setGrossWt(String grossWt) {
this.grossWt = grossWt;
}
/**
*
* #return
* The stoneWt
*/
public String getStoneWt() {
return stoneWt;
}
/**
*
* #param stoneWt
* The stone_wt
*/
public void setStoneWt(String stoneWt) {
this.stoneWt = stoneWt;
}
/**
*
* #return
* The stoneAmt
*/
public String getStoneAmt() {
return stoneAmt;
}
/**
*
* #param stoneAmt
* The stone_amt
*/
public void setStoneAmt(String stoneAmt) {
this.stoneAmt = stoneAmt;
}
/**
*
* #return
* The rate
*/
public String getRate() {
return rate;
}
/**
*
* #param rate
* The rate
*/
public void setRate(String rate) {
this.rate = rate;
}
/**
*
* #return
* The making
*/
public String getMaking() {
return making;
}
/**
*
* #param making
* The making
*/
public void setMaking(String making) {
this.making = making;
}
/**
*
* #return
* The qty
*/
public String getQty() {
return qty;
}
/**
*
* #param qty
* The qty
*/
public void setQty(String qty) {
this.qty = qty;
}
/**
*
* #return
* The netRate
*/
public String getNetRate() {
return netRate;
}
/**
*
* #param netRate
* The net_rate
*/
public void setNetRate(String netRate) {
this.netRate = netRate;
}
/**
*
* #return
* The itemTotal
*/
public String getItemTotal() {
return itemTotal;
}
/**
*
* #param itemTotal
* The item_total
*/
public void setItemTotal(String itemTotal) {
this.itemTotal = itemTotal;
}
/**
*
* #return
* The sumTotal
*/
public String getSumTotal() {
return sumTotal;
}
/**
*
* #param sumTotal
* The sum_total
*/
public void setSumTotal(String sumTotal) {
this.sumTotal = sumTotal;
}
}
I'm implementing a retrofit 2 interface to parse JSON elements (video urls, thumbnails, title etc.)
JSONschema2Pojo resulted in 4 pojo classes, but the main/root one is VideoInfo (never mind implements Parcelable, I'm not yet doing anything with it)
Is the lack of #SerializedName("....") affects anything, knowing that this was automatically generated by jsonschema2pojo ? UPDATE : generated new pojo classes, this time with Gson annotations (#SerializedName("") and #Expose) but still having the same problem.
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class VideoInfo implements Parcelable {
private List<Item> items = new ArrayList<Item>();
private int pageNumber;
private int pageSize;
private int totalCount;
/**
* No args constructor for use in serialization
*
*/
public VideoInfo() {
}
/**
*
* #param totalCount
* #param items
* #param pageSize
* #param pageNumber
*/
public VideoInfo(List<Item> items, int pageNumber, int pageSize, int totalCount) {
this.items = items;
this.pageNumber = pageNumber;
this.pageSize = pageSize;
this.totalCount = totalCount;
}
/**
*
* #return
* The items
*/
public List<Item> getItems() {
return items;
}
/**
*
* #param items
* The items
*/
public void setItems(List<Item> items) {
this.items = items;
}
/**
*
* #return
* The pageNumber
*/
public int getPageNumber() {
return pageNumber;
}
/**
*
* #param pageNumber
* The page_number
*/
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
/**
*
* #return
* The pageSize
*/
public int getPageSize() {
return pageSize;
}
/**
*
* #param pageSize
* The page_size
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
*
* #return
* The totalCount
*/
public int getTotalCount() {
return totalCount;
}
/**
*
* #param totalCount
* The total_count
*/
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
UPDATE: in the class VideoInfo above you can see private List<Item> items = new ArrayList<Item>(); this is because there's another pojo class that has a list of tiems, as follows:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;
public class Item {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("shortDescription")
#Expose
private String shortDescription;
#SerializedName("creationDate")
#Expose
private String creationDate;
#SerializedName("publishedDate")
#Expose
private String publishedDate;
#SerializedName("linkURL")
#Expose
private String linkURL;
#SerializedName("linkText")
#Expose
private String linkText;
#SerializedName("tags")
#Expose
private List<String> tags = new ArrayList<String>();
#SerializedName("videoStillURL")
#Expose
private String videoStillURL;
#SerializedName("thumbnailURL")
#Expose
private String thumbnailURL;
#SerializedName("length")
#Expose
private int length;
#SerializedName("renditions")
#Expose
private List<Rendition> renditions = new ArrayList<Rendition>();
#SerializedName("IOSRenditions")
#Expose
private List<IOSRendition> IOSRenditions = new ArrayList<IOSRendition>();
#SerializedName("HDSRenditions")
#Expose
private List<Object> HDSRenditions = new ArrayList<Object>();
/**
* No args constructor for use in serialization
*
*/
public Item() {
}
/**
*
* #param tags
* #param videoStillURL
* #param HDSRenditions
* #param id
* #param creationDate
* #param IOSRenditions
* #param linkText
* #param shortDescription
* #param renditions
* #param name
* #param linkURL
* #param length
* #param publishedDate
* #param thumbnailURL
*/
public Item(int id, String name, String shortDescription, String creationDate, String publishedDate, String linkURL, String linkText, List<String> tags, String videoStillURL, String thumbnailURL, int length, List<Rendition> renditions, List<IOSRendition> IOSRenditions, List<Object> HDSRenditions) {
this.id = id;
this.name = name;
this.shortDescription = shortDescription;
this.creationDate = creationDate;
this.publishedDate = publishedDate;
this.linkURL = linkURL;
this.linkText = linkText;
this.tags = tags;
this.videoStillURL = videoStillURL;
this.thumbnailURL = thumbnailURL;
this.length = length;
this.renditions = renditions;
this.IOSRenditions = IOSRenditions;
this.HDSRenditions = HDSRenditions;
}
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The name
*/
public String getName() {
return name;
}
/**
*
* #param name
* The name
*/
public void setName(String name) {
this.name = name;
}
/**
*
* #return
* The shortDescription
*/
public String getShortDescription() {
return shortDescription;
}
/**
*
* #param shortDescription
* The shortDescription
*/
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
*
* #return
* The creationDate
*/
public String getCreationDate() {
return creationDate;
}
/**
*
* #param creationDate
* The creationDate
*/
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
/**
*
* #return
* The publishedDate
*/
public String getPublishedDate() {
return publishedDate;
}
/**
*
* #param publishedDate
* The publishedDate
*/
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
/**
*
* #return
* The linkURL
*/
public String getLinkURL() {
return linkURL;
}
/**
*
* #param linkURL
* The linkURL
*/
public void setLinkURL(String linkURL) {
this.linkURL = linkURL;
}
/**
*
* #return
* The linkText
*/
public String getLinkText() {
return linkText;
}
/**
*
* #param linkText
* The linkText
*/
public void setLinkText(String linkText) {
this.linkText = linkText;
}
/**
*
* #return
* The tags
*/
public List<String> getTags() {
return tags;
}
/**
*
* #param tags
* The tags
*/
public void setTags(List<String> tags) {
this.tags = tags;
}
/**
*
* #return
* The videoStillURL
*/
public String getVideoStillURL() {
return videoStillURL;
}
/**
*
* #param videoStillURL
* The videoStillURL
*/
public void setVideoStillURL(String videoStillURL) {
this.videoStillURL = videoStillURL;
}
/**
*
* #return
* The thumbnailURL
*/
public String getThumbnailURL() {
return thumbnailURL;
}
/**
*
* #param thumbnailURL
* The thumbnailURL
*/
public void setThumbnailURL(String thumbnailURL) {
this.thumbnailURL = thumbnailURL;
}
/**
*
* #return
* The length
*/
public int getLength() {
return length;
}
/**
*
* #param length
* The length
*/
public void setLength(int length) {
this.length = length;
}
/**
*
* #return
* The renditions
*/
public List<Rendition> getRenditions() {
return renditions;
}
/**
*
* #param renditions
* The renditions
*/
public void setRenditions(List<Rendition> renditions) {
this.renditions = renditions;
}
/**
*
* #return
* The IOSRenditions
*/
public List<IOSRendition> getIOSRenditions() {
return IOSRenditions;
}
/**
*
* #param IOSRenditions
* The IOSRenditions
*/
public void setIOSRenditions(List<IOSRendition> IOSRenditions) {
this.IOSRenditions = IOSRenditions;
}
/**
*
* #return
* The HDSRenditions
*/
public List<Object> getHDSRenditions() {
return HDSRenditions;
}
/**
*
* #param HDSRenditions
* The HDSRenditions
*/
public void setHDSRenditions(List<Object> HDSRenditions) {
this.HDSRenditions = HDSRenditions;
}
}
UPDATE: So above you can see that we have defined private List<Rendition> renditions = new ArrayList<Rendition>(); that is defined in another pojo classes Rendition.class:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Rendition {
#SerializedName("audioOnly")
#Expose
private boolean audioOnly;
#SerializedName("controllerType")
#Expose
private String controllerType;
#SerializedName("displayName")
#Expose
private String displayName;
#SerializedName("encodingRate")
#Expose
private int encodingRate;
#SerializedName("frameHeight")
#Expose
private int frameHeight;
#SerializedName("frameWidth")
#Expose
private int frameWidth;
#SerializedName("id")
#Expose
private int id;
#SerializedName("referenceId")
#Expose
private Object referenceId;
#SerializedName("remoteStreamName")
#Expose
private Object remoteStreamName;
#SerializedName("remoteUrl")
#Expose
private Object remoteUrl;
#SerializedName("size")
#Expose
private int size;
#SerializedName("uploadTimestampMillis")
#Expose
private int uploadTimestampMillis;
#SerializedName("url")
#Expose
private String url;
#SerializedName("videoCodec")
#Expose
private String videoCodec;
#SerializedName("videoContainer")
#Expose
private String videoContainer;
#SerializedName("videoDuration")
#Expose
private int videoDuration;
/**
* No args constructor for use in serialization
*
*/
public Rendition() {
}
/**
*
* #param controllerType
* #param encodingRate
* #param referenceId
* #param url
* #param size
* #param id
* #param uploadTimestampMillis
* #param frameWidth
* #param remoteUrl
* #param videoContainer
* #param remoteStreamName
* #param displayName
* #param videoCodec
* #param videoDuration
* #param audioOnly
* #param frameHeight
*/
public Rendition(boolean audioOnly, String controllerType, String displayName, int encodingRate, int frameHeight, int frameWidth, int id, Object referenceId, Object remoteStreamName, Object remoteUrl, int size, int uploadTimestampMillis, String url, String videoCodec, String videoContainer, int videoDuration) {
this.audioOnly = audioOnly;
this.controllerType = controllerType;
this.displayName = displayName;
this.encodingRate = encodingRate;
this.frameHeight = frameHeight;
this.frameWidth = frameWidth;
this.id = id;
this.referenceId = referenceId;
this.remoteStreamName = remoteStreamName;
this.remoteUrl = remoteUrl;
this.size = size;
this.uploadTimestampMillis = uploadTimestampMillis;
this.url = url;
this.videoCodec = videoCodec;
this.videoContainer = videoContainer;
this.videoDuration = videoDuration;
}
/**
*
* #return
* The audioOnly
*/
public boolean isAudioOnly() {
return audioOnly;
}
/**
*
* #param audioOnly
* The audioOnly
*/
public void setAudioOnly(boolean audioOnly) {
this.audioOnly = audioOnly;
}
/**
*
* #return
* The controllerType
*/
public String getControllerType() {
return controllerType;
}
/**
*
* #param controllerType
* The controllerType
*/
public void setControllerType(String controllerType) {
this.controllerType = controllerType;
}
/**
*
* #return
* The displayName
*/
public String getDisplayName() {
return displayName;
}
/**
*
* #param displayName
* The displayName
*/
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
/**
*
* #return
* The encodingRate
*/
public int getEncodingRate() {
return encodingRate;
}
/**
*
* #param encodingRate
* The encodingRate
*/
public void setEncodingRate(int encodingRate) {
this.encodingRate = encodingRate;
}
/**
*
* #return
* The frameHeight
*/
public int getFrameHeight() {
return frameHeight;
}
/**
*
* #param frameHeight
* The frameHeight
*/
public void setFrameHeight(int frameHeight) {
this.frameHeight = frameHeight;
}
/**
*
* #return
* The frameWidth
*/
public int getFrameWidth() {
return frameWidth;
}
/**
*
* #param frameWidth
* The frameWidth
*/
public void setFrameWidth(int frameWidth) {
this.frameWidth = frameWidth;
}
/**
*
* #return
* The id
*/
public int getId() {
return id;
}
/**
*
* #param id
* The id
*/
public void setId(int id) {
this.id = id;
}
/**
*
* #return
* The referenceId
*/
public Object getReferenceId() {
return referenceId;
}
/**
*
* #param referenceId
* The referenceId
*/
public void setReferenceId(Object referenceId) {
this.referenceId = referenceId;
}
/**
*
* #return
* The remoteStreamName
*/
public Object getRemoteStreamName() {
return remoteStreamName;
}
/**
*
* #param remoteStreamName
* The remoteStreamName
*/
public void setRemoteStreamName(Object remoteStreamName) {
this.remoteStreamName = remoteStreamName;
}
/**
*
* #return
* The remoteUrl
*/
public Object getRemoteUrl() {
return remoteUrl;
}
/**
*
* #param remoteUrl
* The remoteUrl
*/
public void setRemoteUrl(Object remoteUrl) {
this.remoteUrl = remoteUrl;
}
/**
*
* #return
* The size
*/
public int getSize() {
return size;
}
/**
*
* #param size
* The size
*/
public void setSize(int size) {
this.size = size;
}
/**
*
* #return
* The uploadTimestampMillis
*/
public int getUploadTimestampMillis() {
return uploadTimestampMillis;
}
/**
*
* #param uploadTimestampMillis
* The uploadTimestampMillis
*/
public void setUploadTimestampMillis(int uploadTimestampMillis) {
this.uploadTimestampMillis = uploadTimestampMillis;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The videoCodec
*/
public String getVideoCodec() {
return videoCodec;
}
/**
*
* #param videoCodec
* The videoCodec
*/
public void setVideoCodec(String videoCodec) {
this.videoCodec = videoCodec;
}
/**
*
* #return
* The videoContainer
*/
public String getVideoContainer() {
return videoContainer;
}
/**
*
* #param videoContainer
* The videoContainer
*/
public void setVideoContainer(String videoContainer) {
this.videoContainer = videoContainer;
}
/**
*
* #return
* The videoDuration
*/
public int getVideoDuration() {
return videoDuration;
}
/**
*
* #param videoDuration
* The videoDuration
*/
public void setVideoDuration(int videoDuration) {
this.videoDuration = videoDuration;
}
}
I have created a retrofit interface VideoInterface.class
import retrofit2.Call;
import retrofit2.http.GET;
/**
* retrofit 2 interface
*/
public interface VideoInterface {
String apiURL = ".....";
#GET(apiURL)
public Call<VideosResponse> listVideos();
}
I have created a response/parse class VideosResponse.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.ArrayList;
import java.util.List;
/**
*/
public class VideosResponse {
//initalizing the collection
List<VideoInfo> videos;
public VideosResponse() {
videos = new ArrayList<VideoInfo>();
}
//parsing the response
public static VideosResponse parseJSON(String response) {
Gson gson = new GsonBuilder().create();
VideosResponse videosResponse = gson.fromJson(response, VideosResponse.class);
return videosResponse;
}
}
UPDATED :Finally I'm calling the API , but not able to get the individual elements
I know I should be able to do something like response.body().getItem().getID().getRendition().getUrl() for example, but I don't see it in the auto complete and if I write it I get errors.
This code is in my onResume() method , the reason why I've commented out public static below is because it's not allowed within the onResume()
// Creating a simple REST adapter which points the API
// public static
final String BASE_URL = "http://api......";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
// Creating an instance of our API interface.
VideoInterface service = retrofit.create(VideoInterface.class);
Call<VideosResponse> call = service.listVideos();
call.enqueue(new Callback<VideosResponse>() {
#Override
public void onResponse(Call<VideosResponse> call, Response<VideosResponse> response) {
VideosResponse videoResponse = response.body();
}
#Override
public void onFailure(Call<VideosResponse> call, Throwable t) {
}});
Everything to the last step seems be alright (no errors), the following logs gives me:
Log.d("Videos ", response.message()); //OK
Log.d("Videos ", String.valueOf(response.isSuccess())); //TRUE
Log.d("Videos ", String.valueOf(response.code())); //200
but I'm still not able to get the strings I need. When I print the log for the response show the response VideosResponse videoResponse = response.body(); I get : VideosResponse#3b8bfaa4 , is this normal? how can I use this?
Is using parcelable advised? will it change anything?
You need to show us the json response or you can figure out on your own also. Basically the object attributes name must match the json attributes, you can debug to see whether the elements are receiving the value or not, in case they are not then add the SerializedName annotation to it. From there onwards there are two possibilities either you have an object or an array. For which you can further create a POJO or create a attribute of type List.
I know I should be able to do something like response.body().item.getID() for example
Um, no, not based on the code as I understand it.
response here would appear to be Response<VideosResponse> response
response.body() therefore would be a VideosResponse
response.body().item will fail, as VideosResponse does not have an item field
When I print the log for the response show the response VideosResponse videoResponse = response.body(); I get : VideosResponse#3b8bfaa4 , is this normal?
Yes. That is the default toString() output for a Java object that has not overridden toString(). This shows that response.body() is a VideosResponse.
I have created a response/parse class VideosResponse.java
Then you know that VideosResponse does not have anything named item. Gson does not add methods to your classes; it only populates instances of those classes, based on parsing some JSON.
If you are expecting VideosResponse to have an item field, make sure that exists in your JSON, and then edit VideosResponse to have an item field.
add a toString() to your VideoInfo class and then onResponse you can log the single object of the returned list with something like
for (VideoInfo videoInfo : videoResponses)
Log.d(LOG_TAG, "VideoInfo: " + videoInfo.toString());
So I'm trying to solve a problem that I have with my custom TypeAdapter with Gson and Retrofit. I keep getting a Expected BEGIN_OBJECT but was STRING error but I'm not really sure how to solve it. Previously I was getting a Expected BEGIN_ARRAY but was STRING error and I solved that. I'm not sure if it needs to be the same way with this new error. I've listed my classes below and any help is appreciated. This is what my json looks like here: http://pastie.org/private/bfo86iznldacbz10rtsdsg The main problem is the multimedia field in the json. It's an empty string if there is no value but if there is a value, it returns a jsonarray that contains jsonobjects.
ArrayAdapter.java
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
public class ArrayAdapter<T> extends TypeAdapter<List<T>> {
private Class<T> adapterclass;
public ArrayAdapter(Class<T> adapterclass) {
this.adapterclass = adapterclass;
}
public List<T> read(JsonReader reader) throws IOException {
List<T> list = new ArrayList<T>();
Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(new ArrayAdapterFactory())
.create();
if (reader.peek() == JsonToken.STRING) {
T inning = gson.fromJson(reader, adapterclass);
list.add(inning);
} else if (reader.peek() == JsonToken.BEGIN_ARRAY) {
reader.beginArray();
while (reader.hasNext()) {
T inning = gson.fromJson(reader, adapterclass);
list.add(inning);
}
reader.endArray();
} else if (reader.peek() == JsonToken.BEGIN_OBJECT) {
reader.beginObject();
while(reader.hasNext()) {
}
}
return list;
}
public void write(JsonWriter writer, List<T> value) throws IOException {
}
}
ArraryAdapterFactory
import java.lang.reflect.ParameterizedType;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
public class ArrayAdapterFactory implements TypeAdapterFactory {
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {
TypeAdapter<T> typeAdapter = null;
try {
if (type.getRawType() == List.class)
typeAdapter = new ArrayAdapter(
(Class) ((ParameterizedType) type.getType())
.getActualTypeArguments()[0]);
} catch (Exception e) {
e.printStackTrace();
}
return typeAdapter;
}
}
Times.java
public class NYTimes {
// uses the new york times api
// gets the top stores on the nytimes homepage
private static final String API_URL = "http://api.nytimes.com/svc/news/v3/content/all/all";
static Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
private static final RestAdapter REST_ADAPTER = new RestAdapter.Builder()
.setConverter(new GsonConverter(gson))
.setEndpoint(API_URL)
.build();
private static final NYTimesService SERVICE = REST_ADAPTER.create(NYTimesService.class);
public static NYTimesService getService() {
return SERVICE;
}
}
POJO Classes
News.java
public class News {
#Expose
private String status;
#Expose
private String copyright;
#SerializedName("num_results")
#Expose
private Integer numResults;
#Expose
private List<Result> results = new ArrayList<Result>();
/**
*
* #return
* The status
*/
public String getStatus() {
return status;
}
/**
*
* #param status
* The status
*/
public void setStatus(String status) {
this.status = status;
}
/**
*
* #return
* The copyright
*/
public String getCopyright() {
return copyright;
}
/**
*
* #param copyright
* The copyright
*/
public void setCopyright(String copyright) {
this.copyright = copyright;
}
/**
*
* #return
* The numResults
*/
public Integer getNumResults() {
return numResults;
}
/**
*
* #param numResults
* The num_results
*/
public void setNumResults(Integer numResults) {
this.numResults = numResults;
}
/**
*
* #return
* The results
*/
public List<Result> getResults() {
return results;
}
/**
*
* #param results
* The results
*/
public void setResults(List<Result> results) {
this.results = results;
}
}
Result.java
public class Result {
#Expose
private String section;
#Expose
private String subsection;
#Expose
private String title;
#SerializedName("abstract")
#Expose
private String _abstract;
#Expose
private String url;
#Expose
private String byline;
#SerializedName("thumbnail_standard")
#Expose
private String thumbnailStandard;
#SerializedName("item_type")
#Expose
private String itemType;
#Expose
private String source;
#SerializedName("updated_date")
#Expose
private String updatedDate;
#SerializedName("created_date")
#Expose
private String createdDate;
#SerializedName("published_date")
#Expose
private String publishedDate;
#SerializedName("material_type_facet")
#Expose
private String materialTypeFacet;
#Expose
private String kicker;
#Expose
private String subheadline;
#SerializedName("des_facet")
#Expose
private List<String> desFacet = new ArrayList<>();
#SerializedName("org_facet")
#Expose
private List<String> orgFacet = new ArrayList<>();
#SerializedName("per_facet")
#Expose
private List<String> perFacet = new ArrayList<>();
#SerializedName("geo_facet")
#Expose
private List<String> geoFacet = new ArrayList<>();
#SerializedName("related_urls")
#Expose
private Object relatedUrls;
#Expose
private List<Multimedium> multimedia;
/**
*
* #return
* The section
*/
public String getSection() {
return section;
}
/**
*
* #param section
* The section
*/
public void setSection(String section) {
this.section = section;
}
/**
*
* #return
* The subsection
*/
public String getSubsection() {
return subsection;
}
/**
*
* #param subsection
* The subsection
*/
public void setSubsection(String subsection) {
this.subsection = subsection;
}
/**
*
* #return
* The title
*/
public String getTitle() {
return title;
}
/**
*
* #param title
* The title
*/
public void setTitle(String title) {
this.title = title;
}
/**
*
* #return
* The _abstract
*/
public String getAbstract() {
return _abstract;
}
/**
*
* #param _abstract
* The abstract
*/
public void setAbstract(String _abstract) {
this._abstract = _abstract;
}
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The byline
*/
public String getByline() {
return byline;
}
/**
*
* #param byline
* The byline
*/
public void setByline(String byline) {
this.byline = byline;
}
/**
*
* #return
* The thumbnailStandard
*/
public String getThumbnailStandard() {
return thumbnailStandard;
}
/**
*
* #param thumbnailStandard
* The thumbnail_standard
*/
public void setThumbnailStandard(String thumbnailStandard) {
this.thumbnailStandard = thumbnailStandard;
}
/**
*
* #return
* The itemType
*/
public String getItemType() {
return itemType;
}
/**
*
* #param itemType
* The item_type
*/
public void setItemType(String itemType) {
this.itemType = itemType;
}
/**
*
* #return
* The source
*/
public String getSource() {
return source;
}
/**
*
* #param source
* The source
*/
public void setSource(String source) {
this.source = source;
}
/**
*
* #return
* The updatedDate
*/
public String getUpdatedDate() {
return updatedDate;
}
/**
*
* #param updatedDate
* The updated_date
*/
public void setUpdatedDate(String updatedDate) {
this.updatedDate = updatedDate;
}
/**
*
* #return
* The createdDate
*/
public String getCreatedDate() {
return createdDate;
}
/**
*
* #param createdDate
* The created_date
*/
public void setCreatedDate(String createdDate) {
this.createdDate = createdDate;
}
/**
*
* #return
* The publishedDate
*/
public String getPublishedDate() {
return publishedDate;
}
/**
*
* #param publishedDate
* The published_date
*/
public void setPublishedDate(String publishedDate) {
this.publishedDate = publishedDate;
}
/**
*
* #return
* The materialTypeFacet
*/
public String getMaterialTypeFacet() {
return materialTypeFacet;
}
/**
*
* #param materialTypeFacet
* The material_type_facet
*/
public void setMaterialTypeFacet(String materialTypeFacet) {
this.materialTypeFacet = materialTypeFacet;
}
/**
*
* #return
* The kicker
*/
public String getKicker() {
return kicker;
}
/**
*
* #param kicker
* The kicker
*/
public void setKicker(String kicker) {
this.kicker = kicker;
}
/**
*
* #return
* The subheadline
*/
public String getSubheadline() {
return subheadline;
}
/**
*
* #param subheadline
* The subheadline
*/
public void setSubheadline(String subheadline) {
this.subheadline = subheadline;
}
/**
*
* #return
* The desFacet
*/
public List<String> getDesFacet() {
return desFacet;
}
/**
*
* #param desFacet
* The des_facet
*/
public void setDesFacet(List<String> desFacet) {
this.desFacet = desFacet;
}
/**
*
* #return
* The orgFacet
*/
public List<String> getOrgFacet() {
return orgFacet;
}
/**
*
* #param orgFacet
* The org_facet
*/
public void setOrgFacet(List<String> orgFacet) {
this.orgFacet = orgFacet;
}
/**
*
* #return
* The perFacet
*/
public List<String> getPerFacet() {
return perFacet;
}
/**
*
* #param perFacet
* The per_facet
*/
public void setPerFacet(List<String> perFacet) {
this.perFacet = perFacet;
}
/**
*
* #return
* The geoFacet
*/
public List<String> getGeoFacet() {
return geoFacet;
}
/**
*
* #param geoFacet
* The geo_facet
*/
public void setGeoFacet(List<String> geoFacet) {
this.geoFacet = geoFacet;
}
/**
*
* #return
* The relatedUrls
*/
public Object getRelatedUrls() {
return relatedUrls;
}
/**
*
* #param relatedUrls
* The related_urls
*/
public void setRelatedUrls(Object relatedUrls) {
this.relatedUrls = relatedUrls;
}
/**
*
* #return
* The multimedia
*/
public List<Multimedium> getMultimedia() {
return multimedia;
}
/**
*
* #param multimedia
* The multimedia
*/
public void setMultimedia(List<Multimedium> multimedia) {
this.multimedia = multimedia;
}
}
Multimedium.java
public class Multimedium {
#Expose
private String url;
#Expose
private String format;
#Expose
private Integer height;
#Expose
private Integer width;
#Expose
private String type;
#Expose
private String subtype;
#Expose
private Object caption;
#Expose
private Object copyright;
/**
*
* #return
* The url
*/
public String getUrl() {
return url;
}
/**
*
* #param url
* The url
*/
public void setUrl(String url) {
this.url = url;
}
/**
*
* #return
* The format
*/
public String getFormat() {
return format;
}
/**
*
* #param format
* The format
*/
public void setFormat(String format) {
this.format = format;
}
/**
*
* #return
* The height
*/
public Integer getHeight() {
return height;
}
/**
*
* #param height
* The height
*/
public void setHeight(Integer height) {
this.height = height;
}
/**
*
* #return
* The width
*/
public Integer getWidth() {
return width;
}
/**
*
* #param width
* The width
*/
public void setWidth(Integer width) {
this.width = width;
}
/**
*
* #return
* The type
*/
public String getType() {
return type;
}
/**
*
* #param type
* The type
*/
public void setType(String type) {
this.type = type;
}
/**
*
* #return
* The subtype
*/
public String getSubtype() {
return subtype;
}
/**
*
* #param subtype
* The subtype
*/
public void setSubtype(String subtype) {
this.subtype = subtype;
}
/**
*
* #return
* The caption
*/
public Object getCaption() {
return caption;
}
/**
*
* #param caption
* The caption
*/
public void setCaption(Object caption) {
this.caption = caption;
}
/**
*
* #return
* The copyright
*/
public Object getCopyright() {
return copyright;
}
/**
*
* #param copyright
* The copyright
*/
public void setCopyright(Object copyright) {
this.copyright = copyright;
}
}
I know it's a lot of code to go through but I'm looking for any help to solve this problem so I'm trying to be as clear as I can.
I was able to get a solution by implementing a custom JsonDeserializer and then adding that to the RestAdapter like so:
public class ResultsDeserializerJson implements JsonDeserializer<Result> {
#Override
public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
JsonElement titleElement = json.getAsJsonObject().get("title");
JsonElement multimediaElement = json.getAsJsonObject().get("multimedia");
if (multimediaElement.isJsonArray()) {
return new Result(
titleElement.toString(),
(Multimedia[]) context.deserialize(multimediaElement.getAsJsonArray(), Multimedia[].class));
} else if (multimediaElement.getAsString().equals("")) {
Multimedia multimedia = new Multimedia();
multimedia.setFormat("");
multimedia.setUrl("");
return new Result(titleElement.toString(), multimedia);
} else {
Log.d("ResultsDeserializerJson", multimediaElement.toString());
throw new JsonParseException("Unsupported type of multimedia element");
}
}
}
Inside Result.java I added the following constructor (note you can add more parameters for things like section, subsection, etc.):
public Result(String title, Multimedia ... multimedia) {
this.mTitle = title.replace("\"", "");;
mMultimedia = Arrays.asList(multimedia);
}
Then for my RestAdapter I do the following:
private NYTimesService() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Result.class, new ResultsDeserializerJson()).create();
mAsyncRestAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setConverter(new GsonConverter(gson))
.setRequestInterceptor(new RequestInterceptor() {
#Override
public void intercept(RequestFacade request) {
request.addEncodedQueryParam("api-key", API_KEY);
}
})
.setLogLevel(RestAdapter.LogLevel.FULL)
.build();
}
I created a custom application to get this working and the repository is open sourced here:
SampleNYTimesApp Repo
This is still somewhat of a hackish solution, and I feel like it is not the most optimal, but I was able to get the following in the time I figured out the solution: