JSON deserializer with GSON using HashMap - java

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!

Related

Fetching Nested JSON Arrays with retrofit?

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

IndexOutOfBoundsException: Index: 2, Size: 1 at java.util.ArrayList.get(ArrayList.java:437) [duplicate]

This question already has an answer here:
What is a StringIndexOutOfBoundsException? How can I fix it?
(1 answer)
Closed 2 years ago.
When I set The data it says
String enrloment = studentData.get(position).getEnrollments().get(position).getCourse().getTitle();
this line
java.lang.IndexOutOfBoundsException: Index: 2, Size: 1 at java.util.ArrayList.get(ArrayList.java:437)
my app crashed i am using retrofit library for get data
This My Adapter Class
Blockquote
public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.StudentViewholde> {
private Context context;
private List<StudentInformation>studentData;
public StudentAdapter(Context context, List<StudentInformation> studentData) {
this.context = context;
this.studentData = studentData;
}
public void setStudentData(List<StudentInformation> studentData) {
this.studentData = studentData;
notifyDataSetChanged();
}
#NonNull
#Override
public StudentViewholde onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.single_raw,parent,false);
return new StudentViewholde(view);
}
#Override
public void onBindViewHolder(#NonNull StudentViewholde holder, int position) {
StudentInformation studentInformation = studentData.get(position);
holder.idTv.setText(studentInformation.getID().toString());
holder.nameTv.setText(studentInformation.getFirstMidName());
holder.enrolmentId.setText(studentInformation.getEnrollments().get(position).getStudentID().toString());
}
#Override
public int getItemCount() {
return studentData.size();
}
class StudentViewholde extends RecyclerView.ViewHolder{
TextView idTv,nameTv,enrolmentId;
public StudentViewholde(#NonNull View itemView) {
super(itemView);
idTv = itemView.findViewById(R.id.idTv);
nameTv = itemView.findViewById(R.id.name);
enrolmentId = itemView.findViewById(R.id.enrollmentDate);
}
}
}
it is my Student Information Pojo class
public class StudentInformation {
#SerializedName("Enrollments")
#Expose
private List<Enrollment> enrollments ;
#SerializedName("ID")
#Expose
private Integer iD;
#SerializedName("LastName")
#Expose
private String lastName;
#SerializedName("FirstMidName")
#Expose
private String firstMidName;
#SerializedName("EnrollmentDate")
#Expose
private String enrollmentDate;
public List<Enrollment> getEnrollments() {
return enrollments;
}
public void setEnrollments(List<Enrollment> enrollments) {
this.enrollments = enrollments;
}
public Integer getID() {
return iD;
}
public void setID(Integer iD) {
this.iD = iD;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstMidName() {
return firstMidName;
}
public void setFirstMidName(String firstMidName) {
this.firstMidName = firstMidName;
}
public String getEnrollmentDate() {
return enrollmentDate;
}
public void setEnrollmentDate(String enrollmentDate) {
this.enrollmentDate = enrollmentDate;
}
}
it is my enrollment pojo class
public class Enrollment {
#SerializedName("Course")
#Expose
private Course course;
#SerializedName("EnrollmentID")
#Expose
private Integer enrollmentID;
#SerializedName("CourseID")
#Expose
private Integer courseID;
#SerializedName("StudentID")
#Expose
private Integer studentID;
#SerializedName("Grade")
#Expose
private Integer grade;
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
public Integer getEnrollmentID() {
return enrollmentID;
}
public void setEnrollmentID(Integer enrollmentID) {
this.enrollmentID = enrollmentID;
}
public Integer getCourseID() {
return courseID;
}
public void setCourseID(Integer courseID) {
this.courseID = courseID;
}
public Integer getStudentID() {
return studentID;
}
public void setStudentID(Integer studentID) {
this.studentID = studentID;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
}
The exception means that you are trying to access the third element (Index: 2) of a list of size 1 (Size: 1). The line of code where you get the error is:
String enrloment = studentData.get(position).getEnrollments().get(position).getCourse().getTitle();
In this line you try to access studentData and enrollments with the method .get(position). The index you use is position which I assume is equal to 2. So the issue is that studentData or enrollments have less than 3 elements inside.
Change this
String enrloment = studentData.get(position).getEnrollments().get(position).getCourse().getTitle();
to
ArrayList<Enrollment> enrloment = studentData.get(position).getEnrollments()
ArrayList<String> enrolmentData = new ArrayList();
for(int i =0;i<enrloment.size();i++){
enrolmentData.add(enrloment.get(i).getCourse().getTitle());
}
Hope it helps
let's say you have 5 students in studentInfoList. and the 3rd student has only 2 enrollments.
if you try String enrloment = studentData.get(position).getEnrollments().get(position).getCourse().getTitle();
i.e, String enrloment = studentData.get(2).getEnrollments().get(2).getCourse().getTitle();
here is the problem. you got only 2 enrollments and calling for the 3rd enrollment which is not there.. hope you got it.

Getting Null object in HashMap implementation

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();

how to get json array into dialog fragment

I have an issue in a dailog fragment. I want to get a json array into the dailog fragment, but I don't know how to do it, here is what am trying. Any suggetion's ?
public class MyAlertSortDialogFragmentIndividual extends DialogFragment {
public static final String DATA = "items";
public static final String SELECTED = "selected";
CharSequence[] cs;
ArrayList<User> transactionList = new ArrayList<>();
List <User> users;
String s;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
users=new ArrayList<>();
Bundle bundle = getArguments();
AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
dialog.setTitle("Sort By");
dialog.setPositiveButton("Cancel", new PositiveButtonClickListener());
bundle.putSerializable("key", transactionList);
String str = bundle.getString("str");
users = new Gson().fromJson(str,ArrayList.class);
return dialog.create();
}
class PositiveButtonClickListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
DialogInterface.OnClickListener selectItemListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// process
//which means position
dialog.dismiss();
}
};
how should I get the data from model class.
public class NewItem {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
If this is your model class then to get data:
String userName,age;
for (NewItem item : users) {
if(item.getName().equals(REQUIRED_USERNAME)){
userName = item.getName();
age = item.getAge();
}
}
First the json format you get is not valid json format send json format like
{
"Users": [
{
"username": "ashish",
"userid": "97"
}
]
}
not like -"Users": [ { "username": "ashish", "userid": "97" } ]
after that map this into class
public class UsersResponce implements Serializable {
#SerializedName("Users")
#Expose
private List<User> users = null;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public class User implements Serializable{
#SerializedName("username")
#Expose
private String username;
#SerializedName("userid")
#Expose
private String userid;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
}
}
Than pass that str value and get Pojo Class like
UsersResponce users = new Gson().fromJson(str,UsersResponce.class);
if(null!=UsersResponce){
List<User> usersList =UsersResponce.getUsers();
if(null!=usersList&&usersList.size()>0){
for (User item : usersList) {
if(item.getUserid().equals(CURRENT_LOGIN_USERID)){
//than set your adapter selcted here
}
}
}
}
For single choice adapter refer this link

Null pointer when trying to access POJO attribute

I am using Retrofit 2 to consume an JSON API, I have the following JSON structure
{
"data": {
"id": 1,
"name": "Josh"
}
}
My User POJO looks like:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And my User interface
#GET("/api/v1/me")
Call<User> me();
But I when I try and do response.body().getName() I get a null pointer exception.
The code which is making the request
UserService userService = ServiceGenerator.createService(UserService.class)
Call<User> call = userService.me();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getName().toString());
}
}
#Override
public void onFailure(Throwable t) {
Log.i("hello", t.getMessage());
}
});
You should create the POJO classes as follows:
POJO for json response:
public class User {
private Data data;
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
POJO for internal Data:
public class Data {
private int id;
private String name;
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;
}
}
Than use response.body().getData().getName() to access name in response.
public class Data {
private User data;
public String getData() {
return data;
}
public void setName(User data) {
this.data = data;
}
}
Access it like this
public void onResponse(Response<Data> response, Retrofit retrofit) {
if(response.isSuccess()) {
Log.i("user", response.body().getData().getName().toString());
}
}

Categories