how to convert JSON string from GSON library to JSON Object? - java

I know some threads have similar question, but I can't find the solution for me.
I am a beginner in mobile development. I little bit confused how to convert JSON string to normal JSON.
so I have JSON as string like below, this json string is generated from GSON that convert Java object to this JSON string:
products=%5B%7B%22customers_basket_date_added%22%3A%222019-04-22%2012%3A28%3A41%22%2C%22customers_basket_id%22%3A4%2C%22customers_basket_product%22%3A%7B%22attributes%22%3A%5B%5D%2C%22attributes_price%22%3A%220.0%22%2C%22categories_id%22%3A8%2C%22categories_name%22%3A%22Kemasan%20Botol%22%2C%22customers_basket_quantity%22%3A6%2C%22images%22%3A%5B%5D%2C%22isSale_product%22%3A%220%22%2C%22language_id%22%3A0%2C%22motorist_id%22%3A0%2C%22motorist_name%22%3A%22%22%2C%22id_jenis_products%22%3A0%2C%22qty_orders_max%22%3A12%2C%22qty_orders_min%22%3A6%2C%22qty_promo_bought%22%3A0%2C%22trans_limit%22%3A0%2C%22trans_live%22%3A0%2C%22manufacturers_id%22%3A0%2C%22parent_id%22%3A0%2C%22products_description%22%3A%22PROMO%20APRIL%20MURAH%21%5Cu003cbr%5Cu003e%5Cr%5CnRekomendasi%20harga%20jual%20warung%20Rp%203.500%2Fbotol%5Cu003cbr%5Cu003e%5Cr%5CnUntung%20Rp%201.300%20%2859%25%29%5Cu003cbr%5Cu003e%5Cr%5CnPembelian%20min%206%20botol%2C%20maks%2012%20botol%22%2C%22final_price%22%3A%222200.0%22%2C%22products_id%22%3A140%2C%22products_image%22%3A%22resources%2Fassets%2Fimages%2Fproduct_images%2F1555722212.promo-larutan-kakitiga.jpg%22%2C%22products_liked%22%3A0%2C%22products_model%22%3A%22%22%2C%22products_name%22%3A%22PROMO%20Cap%20Kaki%20Tiga%20Botol%20200%20ml%22%2C%22products_ordered%22%3A0%2C%22products_price%22%3A%222200.0%22%2C%22products_quantity%22%3A1%2C%22products_status%22%3A0%2C%22products_tax_class_id%22%3A0%2C%22products_viewed%22%3A0%2C%22products_weight%22%3A%221%22%2C%22products_weight_unit%22%3A%22Btl%22%2C%22sort_order%22%3A0%2C%22tax_class_id%22%3A0%2C%22tax_priority%22%3A0%2C%22tax_rates_id%22%3A0%2C%22tax_zone_id%22%3A0%2C%22total_price%22%3A%2213200.0%22%7D%2C%22customers_basket_product_attributes%22%3A%5B%5D%2C%22customers_id%22%3A0%7D%5D&status=0
that JSON string is generated from
new Gson().toJson(cartItemsList)
and that cartItemsList is an instance of class CartProduct
public class CartProduct {
#SerializedName("customers_id")
#Expose
private int customersId;
#SerializedName("customers_basket_id")
#Expose
private int customersBasketId;
#SerializedName("customers_basket_date_added")
#Expose
private String customersBasketDateAdded;
#SerializedName("customers_basket_product")
#Expose
private ProductDetails customersBasketProduct;
#SerializedName("customers_basket_product_attributes")
#Expose
private List<CartProductAttributes> customersBasketProductAttributes = new ArrayList<CartProductAttributes>();
public int getCustomersId() {
return customersId;
}
public void setCustomersId(int customersId) {
this.customersId = customersId;
}
public int getCustomersBasketId() {
return customersBasketId;
}
public void setCustomersBasketId(int customersBasketId) {
this.customersBasketId = customersBasketId;
}
public String getCustomersBasketDateAdded() {
return customersBasketDateAdded;
}
public void setCustomersBasketDateAdded(String customersBasketDateAdded) {
this.customersBasketDateAdded = customersBasketDateAdded;
}
public ProductDetails getCustomersBasketProduct() {
return customersBasketProduct;
}
public void setCustomersBasketProduct(ProductDetails customersBasketProduct) {
this.customersBasketProduct = customersBasketProduct;
}
public List<CartProductAttributes> getCustomersBasketProductAttributes() {
return customersBasketProductAttributes;
}
public void setCustomersBasketProductAttributes(List<CartProductAttributes> customersBasketProductAttributes) {
this.customersBasketProductAttributes = customersBasketProductAttributes;
}
}
and the class CartProductAttributes
public class CartProductAttributes implements Parcelable {
#SerializedName("customers_basket_id")
#Expose
private int customersBasketId;
#SerializedName("products_id")
#Expose
private String productsId;
#SerializedName("option")
#Expose
private Option option;
#SerializedName("values")
#Expose
private List<Value> values = new ArrayList<Value>();
public CartProductAttributes() {
}
public int getCustomersBasketId() {
return customersBasketId;
}
public void setCustomersBasketId(int customersBasketId) {
this.customersBasketId = customersBasketId;
}
public String getProductsId() {
return productsId;
}
public void setProductsId(String productsId) {
this.productsId = productsId;
}
/**
*
* #return
* The option
*/
public Option getOption() {
return option;
}
/**
*
* #param option
* The option
*/
public void setOption(Option option) {
this.option = option;
}
/**
*
* #return
* The values
*/
public List<Value> getValues() {
return values;
}
/**
*
* #param values
* The values
*/
public void setValues(List<Value> values) {
this.values = values;
}
//********** Describes the kinds of Special Objects contained in this Parcelable Instance's marshaled representation *********//
#Override
public int describeContents() {
return 0;
}
//********** Writes the values to the Parcel *********//
public void writeToParcel(Parcel parcel_out, int flags) {
parcel_out.writeValue(customersBasketId);
parcel_out.writeValue(productsId);
parcel_out.writeParcelable(option, flags);
parcel_out.writeList(values);
}
//********** Generates Instances of Parcelable class from a Parcel *********//
public static final Creator<CartProductAttributes> CREATOR = new Creator<CartProductAttributes>() {
// Creates a new Instance of the Parcelable class, Instantiating it from the given Parcel
#Override
public CartProductAttributes createFromParcel(Parcel parcel_in) {
return new CartProductAttributes(parcel_in);
}
// Creates a new array of the Parcelable class
#Override
public CartProductAttributes[] newArray(int size) {
return new CartProductAttributes[size];
}
};
//********** Retrieves the values from the Parcel *********//
protected CartProductAttributes(Parcel parcel_in) {
this.customersBasketId = parcel_in.readInt();
this.productsId = parcel_in.readString();
this.option = parcel_in.readParcelable(Option.class.getClassLoader());
this.values = new ArrayList<Value>();
parcel_in.readList(values, Value.class.getClassLoader());
}
}
and here is the ProductDetails class
public class ProductDetails implements Parcelable {
#SerializedName("products_id")
#Expose
private int productsId;
#SerializedName("products_quantity")
#Expose
private int productsQuantity;
#SerializedName("products_model")
#Expose
private String productsModel;
#SerializedName("products_image")
#Expose
private String productsImage;
#SerializedName("products_price")
#Expose
private String productsPrice;
#SerializedName("discount_price")
#Expose
private String discountPrice;
#SerializedName("products_date_added")
#Expose
private String productsDateAdded;
#SerializedName("products_last_modified")
#Expose
private String productsLastModified;
#SerializedName("products_date_available")
#Expose
private String productsDateAvailable;
#SerializedName("products_weight")
#Expose
private String productsWeight;
#SerializedName("products_weight_unit")
#Expose
private String productsWeightUnit;
#SerializedName("products_status")
#Expose
private int productsStatus;
#SerializedName("products_ordered")
#Expose
private int productsOrdered;
#SerializedName("products_liked")
#Expose
private int productsLiked;
#SerializedName("language_id")
#Expose
private int languageId;
#SerializedName("products_name")
#Expose
private String productsName;
#SerializedName("products_description")
#Expose
private String productsDescription;
#SerializedName("products_url")
#Expose
private String productsUrl;
#SerializedName("products_viewed")
#Expose
private int productsViewed;
#SerializedName("products_tax_class_id")
#Expose
private int productsTaxClassId;
#SerializedName("tax_rates_id")
#Expose
private int taxRatesId;
#SerializedName("tax_zone_id")
#Expose
private int taxZoneId;
#SerializedName("tax_class_id")
#Expose
private int taxClassId;
#SerializedName("tax_priority")
#Expose
private int taxPriority;
#SerializedName("tax_rate")
#Expose
private String taxRate;
#SerializedName("tax_description")
#Expose
private String taxDescription;
#SerializedName("tax_class_title")
#Expose
private String taxClassTitle;
#SerializedName("tax_class_description")
#Expose
private String taxClassDescription;
#SerializedName("categories_id")
#Expose
private int categoriesId;
#SerializedName("categories_name")
#Expose
private String categoriesName;
#SerializedName("categories_image")
#Expose
private String categoriesImage;
#SerializedName("categories_icon")
#Expose
private String categoriesIcon;
#SerializedName("parent_id")
#Expose
private int parentId;
#SerializedName("sort_order")
#Expose
private int sortOrder;
#SerializedName("isLiked")
#Expose
private String isLiked;
#SerializedName("manufacturers_id")
#Expose
private int manufacturersId;
#SerializedName("manufacturers_name")
#Expose
private String manufacturersName;
#SerializedName("manufacturers_image")
#Expose
private String manufacturersImage;
#SerializedName("manufacturers_url")
#Expose
private String manufacturersUrl;
#SerializedName("date_added")
#Expose
private String dateAdded;
#SerializedName("last_modified")
#Expose
private String lastModified;
#SerializedName("isSale_product")
#Expose
private String isSaleProduct;
#SerializedName("attributes_price")
#Expose
private String attributesPrice;
#SerializedName("final_price")
#Expose
private String productsFinalPrice;
#SerializedName("total_price")
#Expose
private String totalPrice = "";
#SerializedName("customers_basket_quantity")
#Expose
private int customersBasketQuantity;
#SerializedName("images")
#Expose
private List<Image> images = new ArrayList<Image>();
#SerializedName("attributes")
#Expose
private List<Attribute> attributes = new ArrayList<Attribute>();
#SerializedName("motorist_id")
#Expose
private long mMotoristId = 0;
#SerializedName("motorist_name")
#Expose
private String mMotoristName = "";
#SerializedName("qty_orders_min")
#Expose
private int mQuantityMin = 0;
#SerializedName("qty_orders_max")
#Expose
private int mQuantityMax = 0;
#SerializedName("id_jenis_products")
#Expose
private int mProductType = 0;
#SerializedName("trans_limit")
#Expose
private int mQuantityPromoLimit = 0;
#SerializedName("trans_live")
#Expose
private int mQuantityPromoLive = 0;
#SerializedName("qty_promo_bought")
#Expose
private int mQuantityPromoBought = 0;
#Override
public String toString() {
StringBuilder tempToString = new StringBuilder("\n--- ProductDetails ---\n");
tempToString.append("productsId: ").append(productsId).append("\n");
tempToString.append("productsName: ").append(productsName).append("\n");
tempToString.append("categoriesId: ").append(categoriesId).append("\n");
tempToString.append("categoriesName: ").append(categoriesName).append("\n");
tempToString.append("productsQuantity: ").append(productsQuantity).append("\n");
tempToString.append("productsDateAdded: ").append(productsDateAdded).append("\n");
tempToString.append("totalPrice: ").append(totalPrice).append("\n");
tempToString.append("minQuantity: ").append(mQuantityMin).append("\n");
tempToString.append("maxQuantity: ").append(mQuantityMax).append("\n");
tempToString.append("mProductType: ").append(mProductType).append("\n");
tempToString.append("mQuantityPromoLimit: ").append(mQuantityPromoLimit).append("\n");
tempToString.append("mQuantityPromoLive: ").append(mQuantityPromoLive).append("\n");
tempToString.append("mQuantityPromoBought: ").append(mQuantityPromoBought).append("\n");
return tempToString.toString();
}
}
and I want to convert that string JSON to be real JSON, for example like this:
{
"type": "donut",
"name": "Cake",
"toppings": [
{ "id": "5002", "type": "Glazed" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5004", "type": "Maple" }
]
}
so I can read and replicate that JSON, and send it as JSON string from my iOS device to server using swift programming language. because I need to post that JSON string in the request body like this:
I get this JSON string from our android developer. this JSON string is generated from GSON library in Android, and it converts from Java Object to JSON string like that. unfortunately the android developer is also not understand how to convert it to real JSON, not JSON string.

Related

how can i call the list in the resttemplate?

1-this my model object for account , iwant to return a json result for post method and my problem that my code return null .=
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String accountType;
private String title;
private double lockedAmount;
private String lastUpdate;
private double balance;
private String currency;
private String rib;
private String Agency;
private String swiftcode;
private String ribURI;
private boolean canDebit;
private boolean canCredit;
private List<Operation> operation;
private List<Documents> documents;
2-this the class Operation :
public class Operation {
private String Descript;
private String ValueDate;
private String bookDate;
private String Reference;
private Integer Debit;
private Integer Credit;
private Integer ClosingBalance;
}
3-this is what i do in my controller :
//get Operation list by account id
#PostMapping("eAccount/Operations/Account/{id}")
public List<Operation> getOperationsByAccountId(#PathVariable long id, String bookDate) {
return operationService.getOperationsByAccountId(id, bookDate);
}
4-and the service :
//get Operation list by account id
public List<Operation> getOperationsByAccountId(#PathVariable long id, String bookDate) {
Account account = new Account();
account.setId(id);
String url = operationUrl;
account = resttemplate.postForObject(url,account, Account.class);
return account.getOperation();
}
5-i need to return this result :
{ "account": { "id": "100000000137",
"operation": [
{
"bookDate": "20160105 20160201" } ] } }

I'm passing a list of JSON file is not getting display in the Android application

I was Passing a this JSON http://www.mocky.io/v2/5cacde192f000078003a93bb
i was trying to print a just a category_name
I'm not able to get the data list , when i pass the object with out the data list just like http://www.mocky.io/v2/5cb859344c0000092ed3d4df
private Category_name category_name;
public Category_name getCategoryName() {
return category_name;
}
}
public class Category_name {
#SerializedName("category_name")
public String name;
public String getName() {
return name;
}
}````
i can access that through the NewAdapter.java
with the following code
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
Log.e("Its coming","NewAdapter");
ApiObject apiObject = apiObjectList.get(position);
holder.title.setText(apiObject.getCategoryName().getName());
}
with the same code I'm not able to get the data list
#SerializedName("data")
public List<Data> data;
public List<Data> getData() {
return data;
}
public class Data {
#SerializedName("details")
private Category_name category_name;
public Category_name getCategoryName() {
return category_name;
}
}
public class Category_name {
#SerializedName("category_name")
public String name;
public String getName() {
return name;
}
}
#Override
public void onBindViewHolder(NewsViewHolder holder, int position) {
Log.e("Its coming","NewAdapter");
ApiObject apiObject = apiObjectList.get(position);
holder.title.setText(apiObject.getData().getCategoryName().getName());
}
I'm not able to access the getCategoryName();
Please help thanks in advance
use json 2 pojo conversion to create proper model class of json data
http://www.jsonschema2pojo.org/
pass whole example object to adapter constructer.
I think you need to follow these way of POJO parsing according to your JSON response.
public class Data{
#Serialization("status")
#Expose
private String status;
#Serialization("data")
#Expose
private List<MyData> data;
Then
public class MyData{
#Serialization("details")
#Expose
private List<Details> getDetails();
#Serialization("product_count")
#Expose
private String Product_count;
#Serialization("products")
#Expose
private List<Products> getProducts();
//setter and getters
}
Details POJO
Public class Details{
#Serialization("category_id")
#Expose
private String category_id;
#Serialization("category_name")
#Expose
private String category_name;
#Serialization("category_icon")
#Expose
private String category_icon;
//setter and getters
}
Products POJO
Public class Products{
#Serialization("product_id")
#Expose
private String product_id;
#Serialization("product_name")
#Expose
private String product_name;
#Serialization("product_image")
#Expose
private String product_icon;
etc
//setter and getters
}

Having Error while working with Retrofit lib. JsonSyntaxException

I am practising with retrofit and i am having an error as
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was NUMBER at line 1 column 31 path $.total_results
I am using this api https://api.themoviedb.org/3/movie/550?api_key=########################
here is my code
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String Tag=MainActivity.class.getSimpleName();
private static final String APIKEY="###########################";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressDialog pDialog= new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
final RecyclerView recyclerView =(RecyclerView)findViewById(R.id.recyclerMovie);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ApiInterface apiService= ApiClient.getClient().create(ApiInterface.class);
Call<MovieResponse> call =apiService.getTopRatedMovie(APIKEY);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse> call, Response<MovieResponse> response) {
List<Movie> movies=response.body().getResults();
Log.d(Tag, "Numbers Of Movies Received"+ movies.size());
MovieAdapter adapter =new MovieAdapter(movies,R.layout.list_item_movies,getApplicationContext());
recyclerView.setAdapter(adapter);
pDialog.dismiss();
}
#Override
public void onFailure(Call<MovieResponse> call, Throwable t) {
Log.d(Tag,"Error:-"+t.toString());
pDialog.dismiss();
Toast.makeText(getApplicationContext(),"Oops Error...",Toast.LENGTH_SHORT).show();
}
});
}}
Movie.java
public class Movie {
#SerializedName("poster_path")
#Expose
private String posterPath;
#SerializedName("adult")
#Expose
private boolean adult;
#SerializedName("overview")
#Expose
private String overview;
#SerializedName("release_date")
#Expose
private String releaseDate;
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds = new ArrayList<Integer>();
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("original_title")
#Expose
private String originalTitle;
#SerializedName("original_language")
#Expose
private String originalLanguage;
#SerializedName("title")
#Expose
private String title;
#SerializedName("backdrop_path")
#Expose
private String backdropPath;
#SerializedName("popularity")
#Expose
private Double popularity;
#SerializedName("vote_count")
#Expose
private Integer voteCount;
#SerializedName("video")
#Expose
private Boolean video;
#SerializedName("vote_average")
#Expose
private Double voteAverage;
public Movie(String posterPath, boolean adult, String overview, String releaseDate, List<Integer> genreIds, Integer id, String originalTitle, String originalLanguage, String title, String backdropPath, Double popularity, Integer voteCount, Boolean video, Double voteAverage) {
this.posterPath = posterPath;
this.adult = adult;
this.overview = overview;
this.genreIds = genreIds;
this.backdropPath = backdropPath;
this.id=id;
this.originalLanguage=originalLanguage;
this.originalTitle=originalTitle;
this.releaseDate=releaseDate;
this.title=title;
this.video=video;
this.voteAverage=voteAverage;
this.voteCount=voteCount;
this.popularity=popularity;
}
//getter and setter methods }
MovieResponse.java
public class MovieResponse {
#SerializedName("page")
#Expose
private int page;
#SerializedName("results")
#Expose
private List<Movie> results;
#SerializedName("total_pages")
#Expose
private int total_pages;
#SerializedName("total_results")
#Expose
private List<Movie> total_results;
//getter and setter methods}
ApiClient.java
public class ApiClient {
public static final String Base_URl="http://api.themoviedb.org/3/";
public static Retrofit retrofit=null;
public static Retrofit getClient(){
if(retrofit==null){
retrofit=new Retrofit.Builder()
.baseUrl(Base_URl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}}
ApiInterface.java
public interface ApiInterface{
#GET("movie/top_rated")
Call<MovieResponse> getTopRatedMovie(#Query("api_key") String apiKey);
#GET("movie/{id}")
Call<MovieResponse> getMovieDetails(#Path("id") int id, #Query("api_key") String apiKey);
}
Please Give me the solution...
you created wrong object
#SerializedName("total_results")
#Expose
private List<Movie> total_results;
change to
#SerializedName("total_results")
#Expose
private Int total_results;
because as per your error it should be number of result and you created List so it will ask for ARRAY only.
If I am wrong then please copy your response and take pojo class from
http://www.jsonschema2pojo.org/
Look closely to your Movie.java POJO, especially to this field:
#SerializedName("genre_ids")
#Expose
private List<Integer> genreIds = new ArrayList<Integer>();
...which has type of List of Integers. In the JSON that you've provided this array contains an Objects instead of Integer ids. You can represent this object like this:
public class Genre {
#SerializedName("id")
#Expose
private int id;
#SerializedName("name")
#Expose
private String name;
}
Furthermore, the actual name of this array is genres (not the genres_ids). So, to avoid the parsing error the only thing you need is to change the field above to this:
#SerializedName("genres")
#Expose
private List<Genre> genres = new ArrayList< Genre >();
Happy coding! ;)

Using Retrofit 2 but, have Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

I make request get photos from Flickr, using Retrofit 2.
I create a class for parsing it:
public class FlickrResult {
#SerializedName("photos")
#Expose
private FlickrPhotos photos;
#SerializedName("stat")
#Expose
private String stat;
public FlickrPhotos getPhotos() {
return photos;
}
public class FlickrPhotos {
#SerializedName("page")
#Expose
private int page;
#SerializedName("pages")
#Expose
private String pages;
#SerializedName("perpage")
#Expose
private int perpage;
#SerializedName("total")
#Expose
private String total;
#SerializedName("photo")
#Expose
private ArrayList<FlickrPhoto> photo;
public ArrayList<FlickrPhoto> getPhoto() {
return photo;
}
public class FlickrPhoto {
#SerializedName("id")
#Expose
private String id;
#SerializedName("owner")
#Expose
private String owner;
#SerializedName("secret")
#Expose
private String secret;
#SerializedName("server")
#Expose
private String server;
#SerializedName("farm")
#Expose
private int farm;
#SerializedName("title")
#Expose
private String title;
#SerializedName("ispublic")
#Expose
private int ispublic;
#SerializedName("isfriend")
#Expose
private int isfriend;
#SerializedName("isfamily")
#Expose
private int isfamily;
public String getTitle() {
return title;
}
}
}
}
My build request is:
static {
gson = new GsonBuilder()
.setLenient()
.create();
}
#NonNull
private static Retrofit buildRetrofit() {
Log.i(TAG, "onBuildRetrofitApiFactory");
return new Retrofit.Builder()
.baseUrl("https://api.flickr.com/services/")
.client(getClient())
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
Retrofit interface
#GET("rest")
Call<FlickrResult> getPhotos(#Query("method") String method,
#Query("api_key") String key,
#Query("format") String format,
#Query ("nojsoncallbac") String nojsoncallbac
);
Me responsable is success, but problem in parsing. Have exeption:
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
Please guys, i need you help!
Your Retrofit interface is wrong.
The paremeter "nojsoncallbac" is incorrect and should be "nojsoncallback".
This incorrect parameter causes the API to return a different format on the response
jsonFlickrApi({
"photos": {
"page": 1,
"pages": 10,
"perpage": 100,
"total": 1000,
"photo": [
...
]
}
})
Gson is expecting your JSON string to begin with an object opening brace
{
But the string you have passed to it may be starts with an open quotes
""

Retrofit - Android - Expected BEGIN_ARRAY but was BEGIN_OBJECT [duplicate]

This question already has answers here:
Why does Gson fromJson throw a JsonSyntaxException: Expected BEGIN_OBJECT but was BEGIN_ARRAY?
(2 answers)
Closed 6 years ago.
I am trying to parse following JSON data using Retrofit
{
"message": false,
"suggestions": false,
"vehicle": {
"parked": true,
"uin": "15",
"vin": "WBAEG1312MCB42267",
"make": "Bmw",
"model": "E8SERIES",
"color": "Blue",
"year": "1991",
"package": "Premium",
"options": "",
"interior": "Color: Cream, Type:Leather",
"exterior": "",
"activity": "Parked",
"username": "Dhruba Sarma",
"timestamp": "04-Sep, 00:35",
"latlng": {
"lat": 12.899270164792,
"lng": 77.646080134509
}
}
}
I have created my model classes as follows -
VehicleModel.java
`public class VehicleModel {
#SerializedName("message")
#Expose
private Boolean message;
#SerializedName("suggestions")
#Expose
private Boolean suggestions;
#SerializedName("vehicle")
#Expose
private Vehicle vehicle;
public Boolean getMessage() {
return message;
}
public Boolean getSuggestions() {
return suggestions;
}
public Vehicle getVehicle() {
return vehicle;
}
Vehicle.java
`public class Vehicle {
#SerializedName("parked")
#Expose
private Boolean parked;
#SerializedName("uin")
#Expose
private String uin;
#SerializedName("vin")
#Expose
private String vin;
#SerializedName("make")
#Expose
private String make;
#SerializedName("model")
#Expose
private String model;
#SerializedName("color")
#Expose
private String color;
#SerializedName("year")
#Expose
private String year;
#SerializedName("package")
#Expose
private String _package;
#SerializedName("options")
#Expose
private String options;
#SerializedName("interior")
#Expose
private String interior;
#SerializedName("exterior")
#Expose
private String exterior;
#SerializedName("activity")
#Expose
private String activity;
#SerializedName("username")
#Expose
private String username;
#SerializedName("timestamp")
#Expose
private String timestamp;
#SerializedName("latlng")
#Expose
private LatLng latlng;
public Boolean getParked() {
return parked;
}
public String getUin() {
return uin;
}
public String getVin() {
return vin;
}
public String getMake() {
return make;
}
public String getModel() {
return model;
}
public String getColor() {
return color;
}
public String getYear() {
return year;
}
public String getPackage() {
return _package;
}
public String getOptions() {
return options;
}
public String getInterior() {
return interior;
}
public String getExterior() {
return exterior;
}
public String getActivity() {
return activity;
}
public String getUsername() {
return username;
}
public String getTimestamp() {
return timestamp;
}
public LatLng getLatlng() {
return latlng;
}
}`
And finally LatLng.java
`public class LatLng {
#SerializedName("lat")
#Expose
private Double lat;
#SerializedName("lng")
#Expose
private Double lng;
public Double getLat() {
return lat;
}
public Double getLng() {
return lng;
}
I even tried using jsonschema2pojo for reference. But i still get the below error
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
Please suggest what am i doing wrong ?
EDIT- Here is how i am parsing JSON
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create()).build();
VehicleRequestInterface request = retrofit.create(VehicleRequestInterface.class);
Call<VehicleJSONResponse> call = request.getVehicleJSON(url);
call.enqueue(new Callback<VehicleJSONResponse>() {
#Override
public void onResponse(Call<VehicleJSONResponse> call, Response<VehicleJSONResponse> response) {
VehicleJSONResponse jsonResponse = response.body();
vehicleData = new ArrayList<>(Arrays.asList(jsonResponse.getVehicle()));
Declare your vehicleData variable like this .
ArrayList<VehicleModel> vehicleData = new ArrayList<VehicleModel>();
And then in onResponse rather than
vehicleData = new ArrayList<>(Arrays.asList(jsonResponse.getVehicle()));
add like this way
vehicleData.add(jsonResponse.getVehicle())
The problem is you have no arrays in your json

Categories

Resources