Iam trying t get values from a HashMap but when i call him and setText the value i always get Null, let me show the code:
MyValues.class
private List<ItemsBean> items;
public List<ItemsBean> getItems() { return items;}
public void setItems(List<ItemsBean> items) { this.items = items; }
public static class ItemsBean {
private Map<String, leakBean> Gitt;
public Map<String, leakBean> getGitt() { return Gitt;}
public void setGitt(Map<String, leakBean> Gitt) { this.Gitt = Gitt;}
public static class leakBean {
private int id;
private String dev;
public int getId() {return id; }
public String getDev(){return dev;}
public void setId(int id) { this.id = id;}
public void setDev(String dev){this.dev = dev;}
}
I´m using Gson so for get the values and use it for .setText or Toast im trying to access like this:
MyValues object;
txt1.setText(String.valueOf( object.getItems().get(0).getGitt().get("id")));
Here i get null, can someone helpme with this? i just need to access to values, also the items.size(); return 1 and must return 3
here is hte JSON:
{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": [
{
"987987M7812b163eryrt": {
"id": 1,
"dev": "seed"
},
"90812bn120893juuh": {
"id": 2,
"dev": "none"
},
"981273jn19203nj123rg": {
"id": 3,
"dev": "mine"
}
}
]}
Try with these POJOs:
MyValues.java
public class MyValues {
private int id;
private String name;
private User user;
private List<HashMap<String, ItemsBean>> items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<HashMap<String, ItemsBean>> getItems() {
return items;
}
public void setItems(List<HashMap<String, ItemsBean>> items) {
this.items = items;
}
}
User.java
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
ItemsBean.java
public class ItemsBean {
private int id;
private String dev;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDev() {
return dev;
}
public void setDev(String dev) {
this.dev = dev;
}
}
You can no access the values like so:
object.getItems().get(0).get("987987M7812b163eryrt").getId();
Related
I searched a lot in Google to find a way to use Nested Json Arrays with Retrofit, but it is useless
Most of what I found talks about using JSON Objects with retrofit
And my main issue is how to use the nested Array list inside call method to get data from the server
I have this
JSON
{
"orders": [
{
"ID": "1",
"OrderDate": "2020-07-01",
"order_details": [
{
"detail_ID": "1",
"description": "new order",
"items": [
{
"item_ID": "1",
"item_name": "milk",
"Quantity": "4",
"Price": "56.0",
"UnitOfMeasure": "unit"
},
{
"item_ID": "1",
"item_name": "nuts",
"Quantity": "6",
"Price": "500",
"UnitOfMeasure": "unit"
}
]
}
]
}
]
}
And those my other classes
Item.java
public class Item {
#SerializedName("item_ID")
#Expose
private String itemID;
#SerializedName("item_name")
#Expose
private String itemName;
#SerializedName("Quantity")
#Expose
private String quantity;
#SerializedName("Price")
#Expose
private String price;
#SerializedName("UnitOfMeasure")
#Expose
private String unit_Of_Measure;
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUnitOfMeasure() {
return unitOfMeasure;
}
public void setUnitOfMeasure(String unitOfMeasure) {
this.unitOfMeasure = unitOfMeasure;
}
}
Order.java
public class Order {
#SerializedName("orders")
#Expose
private List<Order_> orders = null;
public List<Order_> getOrders() {
return orders;
}
public void setOrders(List<Order_> orders) {
this.orders = orders;
}
}
OrderDetail.java
public class OrderDetail {
#SerializedName("detail_ID")
#Expose
private String detailID;
#SerializedName("description")
#Expose
private String description;
#SerializedName("items")
#Expose
private List<Item> items = null;
public String getDetailID() {
return detailID;
}
public void setDetailID(String detailID) {
this.detailID = detailID;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
Order_.java
public class Order_ {
#SerializedName("ID")
#Expose
private String iD;
#SerializedName("OrderDate")
#Expose
private String orderDate;
#SerializedName("order_details")
#Expose
private List<OrderDetail> orderDetails = null;
public String getID() {
return iD;
}
public void setID(String iD) {
this.iD = iD;
}
public String getOrderDate() {
return orderDate;
}
public void setOrderDate(String orderDate) {
this.orderDate = orderDate;
}
public List<OrderDetail> getOrderDetails() {
return orderDetails;
}
public void setOrderDetails(List<OrderDetail> orderDetails) {
this.orderDetails = orderDetails;
}
}
ApiInterface.java
#GET("orders")
Call<Order> getAllOrders();
Now I want to get order_detail, item data inside this function
order.enqueue(new Callback<Order>() {
#Override
public void onResponse(Call<Order> call, Response<Order> response) {
if(response.isSuccessful()){
//here ..................
}
}
#Override
public void onFailure(Call<TaskResponse> call, Throwable t) {
Log.w(TAG, "onFailure: " + t.getMessage());
}
});
I will be so grateful who can help me
I'm trying to deserialize a JSON data using GSON and helping myself using HashMap<> but i have an error when i set the json string into the java class, the app just stop, and mark the line with the origin of the error:
funt = gson.fromJson(String.valueOf(R.string.json), stack.class);
Note im trying to get the json data to put in custom adapter, heres the code:
1 Question: I´m correctly getting and setting the json string into java class?
2 Question: I´m correctly Maping the Identifier?
(i'm using "identifier" has class name coz i can't make a each class for every item thats why i need mapping) if not can you tell me how?
Java class where i'm trying to put the json string:
public class stack {
private int id;
private String name;
private UserBean user;
private ItemsBean items;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public ItemsBean getItems() {
return items;
}
public void setItems(ItemsBean items) {
this.items = items;
}
public static class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class ItemsBean {
private HashMap<String, IdentifierBean> identifier;
public HashMap<String, IdentifierBean> getIdentifier(){
return identifier;
}
public void setIdentifier(HashMap<String,IdentifierBean> identifier){
this.identifier = identifier;
}
public static class IdentifierBean {
private int id;
private int strong;
private boolean active;
private String sell;
public int getId() {return id;}
public void setId(int id) {this.id = id; }
public int getStrong() {return strong;}
public void setStrong(int strong) {this.strong = strong;}
public boolean isActive() {return active;}
public void setActive(boolean active) {this.active = active;}
public String getSell() {return sell;}
public void setSell(String sell) {this.sell = sell;}
}
}
}
Here is the Activity class:
public class stacker extends AppCompatActivity {
stack funt;
Gson gson;
adapterstack adapter;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stacker);
list = (ListVeew)findViewById(R.id.listss);
gson = new Gson();
funt = gson.fromJson(String.valueOf(R.string.json), stack.class);
adapter = new adapterstack(stacker.this, (List<stack.ItemsBean>) funt.getItems());
list.setAdapter(adapter);
}
}
Here is the Adapter:
public class adapterstack extends BaseAdapter {
List<stack.ItemsBean> itemlist;
Context sContext;
public adapterstack( Context sContext, List<stack.ItemsBean> itemlist) {
this.sContext = sContext;
this.itemlist = itemlist;}
#Override
public int getCount() {return itemlist.size();}
#Override
public Object getItem(int i) {return itemlist.get(i);}
#Override
public long getItemId(int i) {return i;}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) sContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rootView = inflater.inflate(R.layout.item_act, viewGroup, false);
final stack.ItemsBean item = (stack.ItemsBean) getItem(i);
TextView nombre = (TextView) rootView.findViewById(R.id.txt1);
TextView genero = (TextView) rootView.findViewById(R.id.txt2);
//Here i'm trying to get identifier data info from stack.class
nombre.setText(item.getIdentifier().get(i).getId());
genero.setText(item.getIdentifier().get(i).getStrong());
return rootView;
}
}
the JSON:
[{
"id": 1001,
"name": "Super1",
"user": {
"name": "The Super 1"
},
"items": {
"987987M7812b163eryrt": {
"id": 1,
"strong": 456,
"active": true,
"sell": "te"
},
"90812bn120893juuh": {
"id": 2,
"strong": 4700,
"active": true,
"sell": "tt"
},
"981273jn19203nj123rg": {
"id": 3,
"strong": 3000,
"active": true,
"sell": "ti"
}
}}]
I see the JSON string that you are trying to parse is indicating an array. In that case you need to parse the JSON as follows.
funt = gson.fromJson(String.valueOf(R.string.json), stack[].class);
Hope that helps!
This question already has answers here:
Retrofit 2: Get JSON from Response body
(14 answers)
Closed 5 years ago.
How to read this response from retrofit and store to java class and access somewhere ??
{
"user": {
"__v": 0,
"updated_at": "2017-11-08T12:07:46.729Z",
"created_at": "2017-11-08T12:07:46.729Z",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6InRlc3QzIiwidXNlcmlkIjozLCJlbWFpbCI6ImFydWwzQHRlc3QuY29tIiwiYWNjZXNzX2xldmVsIjoiQWRtaW4iLCJfaWQiOiI1YTAyZjM5Mjk5OGM4OTI3MjQxYTQ3N2YiLCJncm91cHMiOlt7ImlkIjoxLCJuYW1lIjoiZGlhbGVyIiwiX2lkIjoiNThiM2JmODI5ZTg2MDFjMDVlNzIxNjI3In1dfQ.VKEt1JoXoL_xfRDrrFK-jVj8zC23j4sqZTT2S3HGMbc",
"username": "test3",
"userid": 3,
"email": "arul3#test.com",
"access_level": "Admin",
"_id": "5a02f392998c8927241a477f",
"groups": [{
"id": 1,
"name": "dialer",
"_id": "58b3bf829e8601c05e721627"
}]
}
}
Create classes from pojo like that then parse to retrofit Convert json response to classes
public class MyPojo{
private User user;
public User getUser ()
{
return user;
}
public void setUser (User user)
{
this.user = user;
}
}
User Class:
public class User{
private String username;
private String updated_at;
private String _id;
private String access_level;
private String email;
private String token;
private String userid;
private String __v;
private String created_at;
private Groups[] groups;
public String getUsername ()
{
return username;
}
public void setUsername (String username)
{
this.username = username;
}
public String getUpdated_at ()
{
return updated_at;
}
public void setUpdated_at (String updated_at)
{
this.updated_at = updated_at;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getAccess_level ()
{
return access_level;
}
public void setAccess_level (String access_level)
{
this.access_level = access_level;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getToken ()
{
return token;
}
public void setToken (String token)
{
this.token = token;
}
public String getUserid ()
{
return userid;
}
public void setUserid (String userid)
{
this.userid = userid;
}
public String get__v ()
{
return __v;
}
public void set__v (String __v)
{
this.__v = __v;
}
public String getCreated_at ()
{
return created_at;
}
public void setCreated_at (String created_at)
{
this.created_at = created_at;
}
public Groups[] getGroups ()
{
return groups;
}
public void setGroups (Groups[] groups)
{
this.groups = groups;
}
}
Groups Class:
public class Groups{
private String id;
private String _id;
private String name;
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String get_id ()
{
return _id;
}
public void set_id (String _id)
{
this._id = _id;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}}
Now follow that put your classes and get desire response Retrofit Json response
I am having my collection like below:
{
"_id" : NumberLong(366),
"file" : "xyz",
"meta" : [{
"owner" : "user123",
"rating": "A"
}]
}
I want to sort the query result based on owner
I have tried the below code but sorting is not working
Can anyone help me on this.
query = new Query();
query.addCriteria(Criteria.where("meta.rating").is("A"));
query.with(new Sort(Sort.Direction.ASC, "meta.owner"));
mongoOperations.find(query, Test.class);
My Test Class:
Here i am having List which is another model
#Document(collection = "Test_Data")
public class Test{
#Id
private long id;
private String file;
private List<MetaList> meta;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public List<MetaList> getMeta() {
return meta;
}
public void setMeta(List<MetaList> meta) {
this.meta= meta;
}
}
My MetaList class:
public class MetaList{
private String owner;
private String rating;
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner= owner;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating= rating;
}
}
I am developing and spring application and for object mapping I am using ModelMapper library.
I am able to map basic class mapping but when I am trying to map 2 collection elements, source is set of enumeration with additional property like name and description and destination is pojo having id, name and description.
I have tried typemap and converters in mapping profile but I am getting exception of mapper.
And the source class is from other application(whose dependency have been added in pom.xml). I also don't want source type as an argument in setter of destination.
Ex.
SOURCE:
public class VType{
private int id;
private String name;
private String description;
}
public class VDTO{
private Set<VType> vTypes;
public Set<VType> getVTypes(){
return this.vTypes;
}
public void setVType() { //here I don't want to pass source type as an argument
//code stuff that I don't know what to do here
}
}
SOURCE ENUM:
public enum SourceVType{
V1(1, "Name1", "Desc1");
V2(2, "Name2", "Desc2");
private Integer id;
private String name;
private String description;
SourceVType(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
//getter-setter
}
Have you tried converter feature of modelmapper. You can use typemap converter to achieve this requirement.
#RunWith(JUnit4.class)
public class TempTest {
#Test
public void TestThis(){
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<SrcClass, DestClass>() {
#Override
protected void configure() {
this.map().setId(this.source.getId());
this.map().setName(this.source.getName());
mapper.createTypeMap(TypeEnum.class, TypeClass.class).setConverter(
new Converter<TypeEnum, TypeClass>() {
#Override
public TypeClass convert(MappingContext<TypeEnum, TypeClass> mappingContext) {
if (mappingContext.getSource() == null) {
return null;
}
TypeEnum typeEnum = mappingContext.getSource();
TypeClass typeClass = new TypeClass();
typeClass.setId(typeEnum.getId());
typeClass.setName(typeEnum.getName());
return typeClass;
}
});
}
});
SrcClass srcObj = new SrcClass();
srcObj.setId(1);
srcObj.setName("name");
srcObj.setTypes(new HashSet<>(Arrays.asList(TypeEnum.TYPE1, TypeEnum.TYPE2)));
DestClass dstObj = mapper.map(srcObj, DestClass.class);
Assert.assertEquals(srcObj.getId(), dstObj.getId());
Assert.assertEquals(srcObj.getName(), dstObj.getName());
Assert.assertEquals(srcObj.getTypes().size(), dstObj.getTypes().size());
for(TypeClass c : dstObj.getTypes()) {
TypeEnum e = TypeEnum.getById(c.getId());
Assert.assertNotNull(e);
Assert.assertTrue(srcObj.getTypes().contains(e));
}
}
public static <Source, Result> Set<Result> convertAll(Set<Source> source, Function<Source, Result> projection)
{
Set<Result> results = new HashSet<>();
if(source == null) return results;
for (Source element : source)
{
results.add(projection.apply(element));
}
return results;
}
public static class SrcClass{
private Integer id;
private String name;
private Set<TypeEnum> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeEnum> getTypes() {
return types;
}
public void setTypes(Set<TypeEnum> types) {
this.types = types;
}
}
public static class DestClass{
private Integer id;
private String name;
private Set<TypeClass> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeClass> getTypes() {
return types;
}
public void setTypes(Set<TypeClass> types) {
this.types = types;
}
}
public static enum TypeEnum{
TYPE1(1, "Type 1")
, TYPE2(2, "Type 2")
, TYPE3(3, "Type 3")
, TYPE4(4, "Type 4");
private Integer id;
private String name;
TypeEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
private static final Map<Integer, TypeEnum> byId = new HashMap<>();
private static final Map<String, TypeEnum> byName = new HashMap<>();
static {
for (TypeEnum e : TypeEnum.values()) {
if (byId.put(e.getId(), e) != null) {
throw new IllegalArgumentException("duplicate id: " + e.getId());
}
if (byName.put(e.getName(), e) != null) {
throw new IllegalArgumentException("duplicate name: " + e.getName());
}
}
}
public Integer getId() {
return this.id;
}
public String getName() { return this.name; }
public static TypeEnum getById(Integer id) {
return byId.get(id);
}
public static TypeEnum getByName(String name) {
return byName.get(name);
}
}
public static class TypeClass{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}