I'm trying to obtain an ArrayList of object and initialize it in a wrapper class,
this is my request;
RestTemplate restTemplate = new RestTemplate();
Inventory i = restTemplate.getForObject("http://localhost:8082/items",Inventory.class);
my response handler;
#RequestMapping(value ="/items", method = RequestMethod.GET)
public ArrayList<Item> getItems() {
return ItemList.getItemList();
}
my ItemList class,
public class ItemList{
//to keep a list of globally available list of orders with the type Item.class objects
private static ArrayList<Item> itemList;
public static ArrayList<Item> getItemList() {
return itemList;
}
public static void setItemList(ArrayList<Item> itemList) {
ItemList.itemList = itemList;
}
public static Item getItemById(String id) throws NoSuchItem {
ArrayList<Item> temp = ItemList.getItemList();
for(Item x:temp){
if(x.getId().equals(id))
return x;
}
throw new NoSuchItem();
}
};
My Inventory class,
public class Inventory{
private ArrayList<Item> itemList;
public ArrayList<Item> getRandomList(int size) {
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Item> temp = this.itemList;
if(size>=itemList.size()){
return itemList;
}
else{
Random rand = new Random();
for(int i=0;i<size;i++){
int j = rand.nextInt(temp.size());
Item random = temp.get(j);
random.generateQuantity();
items.add(random);
temp.remove(random);
}
}
return items;
}
public ArrayList<Item> getItemList() {
return itemList;
}
public void setItemList(ArrayList<Item> itemList) {
this.itemList = itemList;
}
};
and finally my Item class,
public class Item {
private String name ;
private String supplier ;
private String weight;
private String id ;
private String location = "not assigned" ;
private int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getQuantity() {
return quantity;
}
public void generateQuantity(){
Random rand = new Random();
int i = rand.nextInt(100);
if(i<3){
this.quantity = 3;
}
else if(i<33){
this.quantity = 2;
}
else{
this.quantity = 1;
}
}
};
I'm building a microservice project using springboot, my response and ItemList class exist in one service , request and Inventory in the next service and the Item class on both the services, But when i run the method i get an JSON parse error: Cannot deserialize instance of ServiceA.Inventory out of START_ARRAY token, What am i doing wrong here?
PS - a sample response the /items endpoint returns ,
[
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
{
"name": "Kit Kat",
"supplier": "Nestle",
"weight": "1",
"id": "kitkat",
"location": "not asssigned"
},
{
"name": "Double Decker",
"supplier": "Nestle",
"weight": "1",
"id": "dd",
"location": "not asssigned"
}
]
According to yout JSON there is no Inventory in the response. So when you do this:
Inventory i = restTemplate.getForObject("http://localhost:8082/items", Inventory.class);
it complains because your response actually has an array (or list) of Item. Object inventory cannot be instantiated from an arrray. Try this:
Item[] items = restTemplate.getForObject("http://localhost:8082/items", Item[].class);
and it should work.
To have class Inventory deserialized your JSON response should be something like:
{
itemList: [
{
"name": "Mars",
"supplier": "Nestle",
"weight": "1",
"id": "mars",
"location": "not asssigned"
},
...
]
}
But note: There is also a problem with your ItemList. Anyway that is another topic because you should first think whhether your response JSON is ok or not.
I think you need to add a no args constructor to the Item class.
Related
{
"status": true,
"message": [
{
"ID": 1,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 2,
"TFrom": "b",
"TTo": "c"
},
{
"ID": 3,
"TFrom": "b",
"TTo": "c"
}
]
}
This is my JSON result, I'm using Android/Java and what I want is to get each object in the "message" array separated in an array, because each one of them should be in a list item.
Which means my ListView is going to view the "message" content in lists.
It's more like this:
list1= [{"ID": 1, "TFrom": "b", "TTo": "c"}]
list2= [{"ID": 2, "TFrom": "b", "TTo": "c"}]
Message Object Class:
public class MessagesObject {
boolean status;
List<AMessage> message;
public List<AMessage> getMessage() {
return message;
}
public void setMessage(List<AMessage> message) {
this.message = message;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
}
AMessage Class:
public class AMessage {
int ID;
String TFrom;
String TTo;
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getTFrom() {
return TFrom;
}
public void setTFrom(String TFrom) {
this.TFrom = TFrom;
}
public String getTTo() {
return TTo;
}
public void setTTo(String TTo) {
this.TTo = TTo;
}
}
Usage :
String json="you json string";
MessagesObject messagesObject = new Gson().fromJson(jsonToParse, MessagesObject.class);
Ref Gson :
implementation 'com.google.code.gson:gson:2.8.2'
Output:
I'm not sure what you really want, but if you really would like to convert an array into list of arrays, ie.
[1, 2, 3] => [[1], [2], [3]]
You can use this code as a starting point.
List<List<T>> YOUR_LIST_OF_LISTS = message.stream().map((e) -> {
ArrayList<T> temp = new ArrayList<>();
temp.add(e);
return temp;
}).collect(Collectors.toList());
Replace T with some datatype you want, in your case probably JSONObject.
Not android specific, just java codes. I'm not sure why you would want to do something like this tho. Comment below if this is not what you intended.
JSONObject heroObject = data.getJSONObject("favorite");
JSONArray jarray=heroObject.getJSONArray("message");
ArrayList<HashMap<String,String>> array=new ArrayList<>();
//now looping through all the elements of the json array
for (int i = 0; i < jarray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = jarray.getJSONObject(i);
HashMap<String,String> inner=new HashMap<String, String>();
inner.put("id", heroObject.getString("ID"));
inner.put("from", heroObject.getString("TFrom"));
inner.put("to", heroObject.getString("TTo"));
array.add(inner);
}
Use gson library. check below how to implement in project.
build.gradle
implementation 'com.google.code.gson:gson:2.7'
Then create MessageModel.java and MessageBaseModel.java.
MessageModel.java
public class MessageModel {
#SerializedName("ID")
int id;
#SerializedName("TFrom")
String tFrom;
#SerializedName("TTo")
String tTo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String gettFrom() {
return tFrom;
}
public void settFrom(String tFrom) {
this.tFrom = tFrom;
}
public String gettTo() {
return tTo;
}
public void settTo(String tTo) {
this.tTo = tTo;
}
}
MessageBaseModel.java
public class MessageBaseModel {
#SerializedName("status")
boolean status;
#SerializedName("message")
ArrayList<MessageModel> messageModels = new ArrayList<>();
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public ArrayList<MessageModel> getMessageModels() {
return messageModels;
}
public void setMessageModels(ArrayList<MessageModel> messageModels) {
this.messageModels = messageModels;
}
}
Use below code in your main activity:(note: result is your JSON result)
MessageBaseModel messageBaseModel=new Gson().fromJson(result.toString() , MessageBaseModel.class);
ArrayList<MessageModel> messageModels = MessageBaseModel.getMessageModels();
Check below example to get the output:
messageModels.get(0) is your first message object
messageModels.get(0).getId()=1
messageModels.get(0).gettFrom()=b
messageModels.get(1).getId()=2
messageModels.get(2).getId()=3
Sorry for my english.
Try this
List<Map<String,String>> list = new ArrayList<>();
try
{
JSONArray messageArray = response.getJSONArray("message");
for (int i = 0;i<messageArray.length(); i++)
{
Map<String,String> map = new HashMap<>();
JSONObject jsonObject = messageArray.getJSONObject(i);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext())
{
String key = keys.next();
String value = jsonObject.getString(key);
map.put(key,value);
}
list.add(map);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
I'm using retrofit 2 for networking functions in my project, and I'm able to parse the json object responses from the server but now I'm supposed to parse a json array that look like this
[
{
"id_asset": 1,
"id_category": 1,
"id_brand": 2,
"name": "Samsung Galaxy 6",
"status": 1,
"updated_at": "Oct 3, 2016 10:24:28 AM",
"rank": 1,
"rate": {
"id_asset_rate": 2,
"id_asset": 1,
"value": 5000,
"loan_to_value": 50,
"offered": 2500,
"annual_rate": 3,
"quantity": 5,
"created_at": "Oct 23, 2016 5:31:31 AM",
"updated_at": "Oct 23, 2016 5:32:31 AM"
},
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
},
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 2,
"name": "Samsung",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/1"
}
}
},
{
"id_asset": 2,
"id_category": 1,
"id_brand": 1,
"name": "i Phone 5",
"status": 1,
"updated_at": "Oct 3, 2016 8:04:36 AM",
"rank": false,
"rate": null,
"best_rate": false,
"category": {
"id_category": 1,
"id_parent": 0,
"name": "Mobile Phones",
"image": "",
"sort": 1,
"status": 1,
"created_at": null,
"updated_at": null,
"_links": {
"self": {
"href": "/v1/categories/1"
}
}
},
"brand": {
"id_brand": 1,
"name": "Apple",
"status": 1,
"created_at": null,
"updated_at": null
},
"_links": {
"self": {
"href": "/v1/assets/2"
}
}
}
]
This is the response from the server and I created this POJO for the response
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
private class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class AssetCategory {
private Integer id_category;
private Integer id_parent;
private String name;
private String image;
private Integer sort;
private Integer status;
private String created_at;
private String updated_at;
private Links links;
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_parent() {
return id_parent;
}
public void setId_parent(Integer id_parent) {
this.id_parent = id_parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
private class Links {
#SerializedName("self")
#Expose
private Self self;
/**
*
* #return
* The self
*/
public Self getSelf() {
return self;
}
/**
*
* #param self
* The self
*/
public void setSelf(Self self) {
this.self = self;
}
}
private class Self {
#SerializedName("href")
#Expose
private String href;
/**
*
* #return
* The href
*/
public String getHref() {
return href;
}
/**
*
* #param href
* The href
*/
public void setHref(String href) {
this.href = href;
}
}
private class AssetBrand {
private Integer id_brand;
private String name;
private Integer status;
private String created_at;
private String updated_at;
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
private class HasLinked {
private Integer has_linked;
private Links links;
public Integer getHas_linked() {
return has_linked;
}
public void setHas_linked(Integer has_linked) {
this.has_linked = has_linked;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
}
}
}
Is my pojo is right ?
My problem is, I can't parse this response. Any help will be appreciated.
Thanks in advance
EDIT :
This is my request to server (using rest api)
#GET("url")
Call<AssetResponse> getAssetList();
EDIT 2: I've changed the code to List, as suggested by Niko Adrianus Yuwono.
This is the new changes
private void getAssets() {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
final ApiInterface apiInterface = retrofit.create(ApiInterface.class);
final AssetRequest assetRequest = new AssetRequest();
assetRequest.setAcc_tok(ACCESS_TOKEN);
final Call<List<AssetResponse>> assetList = apiInterface.getAssetList();
assetList.enqueue(new Callback <List<AssetResponse>>() {
#Override
public void onResponse(Call<List<AssetResponse>> call, Response<List<AssetResponse>> response) {
int statusCode = response.code();
List<AssetResponse> assetResponseList = response.body();
if (statusCode == 200) {
for (int i = 0; i < assetResponseList.size(); i++ ){
Integer id_asset = assetResponseList.get(i).getId_asset();
Integer id_category = assetResponseList.get(i).getId_category();
Integer status = assetResponseList.get(i).getStatus();
String name = assetResponseList.get(i).getName();
Log.d("Assets ","Asset id_asset bb : " + id_asset);
Log.d("Assets ","Asset id_category bb : " + id_category);
Log.d("Assets ","Asset name bb : " + name);
Log.d("Assets ","Asset status bb : " + status);
Double val = assetResponseList.get(i).getAssetRate().getValue();
Log.d("val ","val is : " +val);
}
} else {
Toast.makeText(getContext(), "network error " + statusCode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<List<AssetResponse>> call, Throwable t) {
Log.d("Asset GET Failure", "onFailure: " + t.getMessage());
//showProgress(false);
}
});
}
and this is the response from the server
D/Assets: Asset id_asset bb : 1 D/Assets: Asset id_category bb : 1 D/Assets: Asset name bb : Samsung Galaxy 6 D/Assets: Asset status
bb : 1 10-26 13:13:17.898 22784-22784/ D/AndroidRuntime: Shutting down
VM 10-26 13:13:17.898 22784-22784/ E/AndroidRuntime: FATAL EXCEPTION:
main Process: , PID: 22784 java.lang.NullPointerException: Attempt to
invoke virtual method 'java.lang.Double
.api.model.AssetResponse$AssetRate.getValue()' on a null object
reference
.AssetDatabaseFragment$2.onResponse(AssetDatabaseFragment.java:133)
retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
android.os.Handler.handleCallback(Handler.java:739)
android.os.Handler.dispatchMessage(Handler.java:95)
android.os.Looper.loop(Looper.java:148)
android.app.ActivityThread.main(ActivityThread.java:5417)
java.lang.reflect.Method.invoke(Native Method)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Whenever I access the inner objects it throws error like the above
Your POJO looks right, but your JSON response is a JSONArray so you need to declare it as a List of Objects rather than an Object
#GET("url")
Call<List<AssetResponse>> getAssetList();
And you need to change your inner class access to public so GSON can see the setter and getter of that class.
Your Json key value data is changing from one index to another.
Wrong Json:
[{
//Make this either integer or boolean
"rank": 1,
// best rate is object here in the next index, it's treated as boolean.
"best_rate": {
"id_asset": "1",
"value": "5000",
"loan_to_value": "50",
"offered": "2500",
"annual_rate": "3",
"quantity": "5",
"rank": "1"
}
},
{
"rank":false,
"best_rate":false,
}
]
I have a complete project shared on github with your json.
https://github.com/lingarajsankaravelu/retrofit2v.git
Retrofit code should be like this as i mentioned in the question comment.
#GET("url")
Call<List<AssetResponse>> getAssetList();
As you have requested to explain the changes in your pojo class it should be like this.
AssetReponse.class:
public class AssetResponse {
private Integer id_asset;
private Integer id_category;
private Integer id_brand;
private String name;
private Integer status;
private String updated_at;
private AssetRate assetRate;
private AssetCategory assetCategory;
private Links links;
private Self self;
private AssetBrand assetBrand;
private HasLinked hasLinked;
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Integer getId_category() {
return id_category;
}
public void setId_category(Integer id_category) {
this.id_category = id_category;
}
public Integer getId_brand() {
return id_brand;
}
public void setId_brand(Integer id_brand) {
this.id_brand = id_brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public AssetRate getAssetRate() {
return assetRate;
}
public void setAssetRate(AssetRate assetRate) {
this.assetRate = assetRate;
}
public AssetCategory getAssetCategory() {
return assetCategory;
}
public void setAssetCategory(AssetCategory assetCategory) {
this.assetCategory = assetCategory;
}
public Links getLinks() {
return links;
}
public void setLinks(Links links) {
this.links = links;
}
public Self getSelf() {
return self;
}
public void setSelf(Self self) {
this.self = self;
}
public AssetBrand getAssetBrand() {
return assetBrand;
}
public void setAssetBrand(AssetBrand assetBrand) {
this.assetBrand = assetBrand;
}
public HasLinked getHasLinked() {
return hasLinked;
}
public void setHasLinked(HasLinked hasLinked) {
this.hasLinked = hasLinked;
}
}
AssetRate.class
public class AssetRate {
private Integer id_asset_rate;
private Integer id_asset;
private Double value;
private Double loan_to_value;
private Double offered;
private Double annual_rate;
private String updated_at;
public Integer getId_asset_rate() {
return id_asset_rate;
}
public void setId_asset_rate(Integer id_asset_rate) {
this.id_asset_rate = id_asset_rate;
}
public Integer getId_asset() {
return id_asset;
}
public void setId_asset(Integer id_asset) {
this.id_asset = id_asset;
}
public Double getValue() {
return value;
}
public void setValue(Double value) {
this.value = value;
}
public Double getLoan_to_value() {
return loan_to_value;
}
public void setLoan_to_value(Double loan_to_value) {
this.loan_to_value = loan_to_value;
}
public Double getOffered() {
return offered;
}
public void setOffered(Double offered) {
this.offered = offered;
}
public Double getAnnual_rate() {
return annual_rate;
}
public void setAnnual_rate(Double annual_rate) {
this.annual_rate = annual_rate;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
}
Seperate your inner class like above. Seperating your inner class model will be useful if you are working on a large project. where you don't have to write the same pojo class again. you can use this seperate class structure instead.
You can use this site to generate POJO class. Just enter your JSON response and choose which JSON type you using like GSON,Jackson.etc. and You get perfect POJO classes. no need to change anything.
http://www.jsonschema2pojo.org/
Your Retrofit interface should be
#GET("url")
Call<List<AssetReponse>> getAssessList();
And make sure that your variable name same with key on JSON Response Or you can use annotation #SerializedName for that & for make it simple you can use JSON to POJO Online converter : http://www.jsonschema2pojo.org/
I have JSON like this
{
"data":
[
{
"id": 1,
"Name": "Choc Cake",
"Image": "1.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
},
{
"name": "1 Bag Beans"
}
]
},
{
"id": 2,
"Name": "Ice Cake",
"Image": "dfdsfdsfsdfdfdsf.jpg",
"Category": "Meal",
"Method": "",
"Ingredients":
[
{
"name": "1 Cup Ice"
}
]
}
]
}
I am using JSON Object to de-Serialize the data
this is what i am trying to
JSONObject jsonObj = new JSONObject(jsonStr);
String first = jsonObj.getJSONObject("data").getString("name");
System.out.println(first);
But a Cant seem to get the name or anything
Not sure what i am doing wrong?
and then i am trying to display it into a listview but haven't got to that part yet
data is a JSON Array, not a JSONObject
try: jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
also note the difference between getString and optString, if you don't want an exception on null use the later.
First parse your Json from below method,
private ArrayList<String> getStringFromJson(String jsonStr)
{
ArrayList<String> mNames = new ArrayList<String>();
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject row = array.getJSONObject(i);
mNames= row.getString("Name");
}
return mNames;
}
try {
JSONObject jsonObj = new JSONObject(jsonStr);
jsonObj.getJSONArray("data").getJSONObject(0).getString("name")
} catch (JSONException e) {
}
Data is a json array. Use getJsonObject for json objects.
Refer to this example to create a ListView and populate it's adapter with data from a json object.
Use GSON instead JSON. Hope it helps you.
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
List<Data> datas= new ArrayList<Data>();
datas= Arrays.asList(gson.fromJson(jsonString, Data[].class));
public class Ingredients {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
public class Data {
private int id;
private String Name;
private String Image;
private String Category;
private String Method;
public List<Ingredients> getIngredients() {
return Ingredients;
}
public void setIngredients(List<Ingredients> ingredients) {
Ingredients = ingredients;
}
private List<Ingredients> Ingredients = new ArrayList<Ingredients>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
public String getCategory() {
return Category;
}
public void setCategory(String category) {
Category = category;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
}
My JSON response has the following structure.
How should i parse it to store in a list in java with the structure maintained.
Does GSON provide a solution or should i use multidimensional array list?
I need to pass each of the tag array to a different view pager what approach should I follow.
{
"tag": [
{
"listing_count": 5,
"listings": [
{
"source": "source1",
"data": {
"image": "image1",
"name": "name1"
},
"name": "name1"
}
]
},
{
"listing_count": 5,
"listings": [
{
"source": "source2",
"data": {
"image": "imag2",
"name": "name2"
},
"name": "name2"
}
]
}
]
}
EDIT:
I have created the classes as suggested in the answer..I am having trouble creating the GSON response class.
This is what I have created:
public GsonRequest(int method, String url, Class<T> clazz,
Listener<T> listener, ErrorListener errorListener, Gson gson) {
super(Method.GET, url, errorListener);
this.mClazz = clazz;
this.mListener = listener;
mGson = gson;
}
The gson class should be something like this:
public class TagList {
ArrayList<Tag> tags;
public static class Tag {
int listing_count;
ArrayList<Listings> listings;
public int getListing_count() {
return listing_count;
}
public void setListing_count(int listing_count) {
this.listing_count = listing_count;
}
public ArrayList<Listings> getListings() {
return listings;
}
public void setListings(ArrayList<Listings> listings) {
this.listings = listings;
}
}
public static class Listings {
String source;
Data data;
String name;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class Data {
String image;
String name;
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I have a json object as like this:
[
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
]
And in java I have two classes order and order details as like this:
1) Order.java
package dto;
import java.util.ArrayList;
public class Order
{
int order_id;
String created_at;
String status;
String device_id;
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDevice_id() {
return device_id;
}
public void setDevice_id(String device_id) {
this.device_id = device_id;
}
public ArrayList<Order_details> getOrderList() {
return orderList;
}
public void setOrderList(ArrayList<Order_details> orderList) {
this.orderList = orderList;
}
public void attachOrderDetails(ArrayList<Order_details> member) {
this.orderList = member;
}
}
2) Order_details.java
package dto;
public class Order_details
{
int item_id;
int quantity;
String item_name;
double price;
public int getItem_id()
{
return item_id;
}
public void setItem_id(int item_id)
{
this.item_id = item_id;
}
public int getQuantity()
{
return quantity;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public String getItem_name()
{
return item_name;
}
public void setItem_name(String item_name)
{
this.item_name = item_name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
now i want to convert above json object to the object of order class
To achieve this i have tried it:
Order order= new Order();
order= gs.fromJson(json,Order.class);
System.out.println("order"+order);
but it throws exception as follows:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapte rFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:791)
at com.google.gson.Gson.fromJson(Gson.java:757)
at com.google.gson.Gson.fromJson(Gson.java:706)
at com.google.gson.Gson.fromJson(Gson.java:678)
Please, help me out to convert my json to my java object.
The first [ in your json says its holding an array or Order objects. So you need to make a list of orders rather than a single order class.
List<Order> order = new ArrayList<Order>();
order = gs.fromJson(json, order.getClass());
System.out.println("order" + order);
Or using type token as
List<Order> order = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>() {}.getType();
order = gs.fromJson(json, listType);
System.out.println("order" + order);
Alternatively to work with your code directly you need to modify your json to
{
"created_at": "2014-07-01 5:01:10",
"status": "in progress",
"device_id": "1234",
"order_details": [
{
"item_id": 1,
"quantity": 2
},
{
"item_id": 2,
"quantity": 3
}
]
}
When you are using GSON,then you should be more aware of case sensitive w.r.t key name and variable name.
either change variable name to
ArrayList<Order_details> order_details= new ArrayList<Order_details>(); instead of
ArrayList<Order_details> orderList= new ArrayList<Order_details>();
or
change json key name to orderList instead of order_details
Your JSON string can not cast directly to your class because your json contain array of the parameters of class Order and to convert it into class object you need list of Order class so that this array can be converted to list of Order.
For that you need to take List<Order> of Order class as shown below :
List<Order> orderList = new ArrayList<Order>();
Type listType = new TypeToken<List<Order>>(){}.getType();
orderList = json.fromJson(jsonStr, listType);
May this will help you.