Real title: How do I convert json to custom object using gson(custom object contains ArrayLists and HashMap)?
Problem:
I added an HashMap to my custom object and since then when im trying to convert JSON to my custom object I get this error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 59 path $[0].currentLesson.students.
What do I need to change? ask for any other info you might need from me and I shall give it to you. Thank you!
Code:
private void initializeDatabase() {
ArrayList<Group> groups = null;
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, MODE_PRIVATE);
Gson gson = new Gson();
String groupsJason = sharedPreferences.getString(Database.GROUPS_STRING, null);
Type typeGroup = new TypeToken<ArrayList<Group>>(){}.getType();
groups = gson.fromJson(groupsJason, typeGroup);
if(groups == null){
groups = new ArrayList<>();
}
Database.setGroups(groups);
}
public class Group {
private String groupName;
private ArrayList<Student> students;
private ArrayList<Lesson> lessons;
private Lesson currentLesson;
public Group(String groupName) {
this.groupName = groupName;
students = new ArrayList<>();
lessons = new ArrayList<>();
}
public Group(String groupName, ArrayList<Student> students) {
this.groupName = groupName;
this.students = students;
lessons = new ArrayList<>();
}
public void setCurrentLesson(String currentLesson) {
this.currentLesson = new Lesson(currentLesson, students);
}
public String getGroupName() {
return groupName;
}
public void setGroupName(String groupName) {
this.groupName = groupName;
}
public ArrayList<Student> getStudents() {
return students;
}
public int getGroupSize() {
return students.size();
}
public Boolean getArrivedToLesson(Student student){
return currentLesson.getArrivedToLesson(student);
}
public Lesson getCurrentLesson() {
return currentLesson;
}
public void saveLesson() {
lessons.add(currentLesson);
}
}
public class Lesson {
private String lessonDate;
private HashMap<Student, Boolean> students;
public Lesson(String lessonDate, ArrayList<Student> students) {
this.lessonDate = lessonDate;
this.students = new HashMap<>();
for (Student student : students) {
this.students.put(student, false);
}
}
public String getLessonDate() {
return lessonDate;
}
public void arrivedToLesson(Student student) {
student.arrivedToLesson();
students.put(student, true);
}
public void didntArriveToLesson(Student student) {
student.didntArriveToLesson();
students.put(student, false);
}
public Boolean getArrivedToLesson(Student student) {
return students.get(student);
}
}
private void saveData(){
group.saveLesson();
SharedPreferences sharedPreferences = getSharedPreferences(Database.SHARED_PREFERENCES_STRING, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String groupsJason = gson.toJson(Database.getGroups());
editor.putString(Database.GROUPS_STRING, groupsJason);
editor.apply();
Toast.makeText(this, String.format(getResources().getString(R.string.saved_attendance), lessonDate), Toast.LENGTH_SHORT).show();
onButtonBackClick();
}
I've managed to solve the problem. The problem was that my map - I changed it to HashMap<String, Object>. The string represents my custom object's main attribute - in my case it's name, the object is a boolean and I casts it when needed.
Related
Need a help about the implementation of how to improve the search accuracy of the elasticSearch logic on the JAVA side which is in the springboot application.
Why I am aiming for search accuracy? Because in the production side whenever I am searching for products using the search bar in the app ex. Laptops it shows different results of product also.
First I have a **controller class ** where the request goes to this endpoint:
#PostMapping("/bsl/view/products/sort-filter")
public Response<SearchByFilterByResponse> viewSortByFilterBy(#RequestBody SearchByDto searchBy) throws IOException{
return Response.success(elasticSearchProductBslService.viewSortByFilterBy(searchBy));
}
RequestBody contains the SearchByDto class where inside of that class I have the filterBy object, where inside of it the structure of query is there.
SearchByDto class:
SearchByDto class
FilterBy class:
private Map<String, List<String>> filter;
private List<KeyValue<String, String>> matches;
private List<KeyValue<String, String>> matchesPartial;
private List<KeyValue<String, String>> matchesNot;
private List<KeyValue<String, RangeValue>> ranges;
private List<String> discludeFieldNotNullAndEmpty;
public List<String> getDiscludeFieldNotNullAndEmpty() {
if(discludeFieldNotNullAndEmpty==null) {
this.discludeFieldNotNullAndEmpty = new ArrayList<>();
}
return discludeFieldNotNullAndEmpty;
}
public void setDiscludeFieldNotNullAndEmpty(List<String> discludeFieldNotNullAndEmpty) {
this.discludeFieldNotNullAndEmpty = discludeFieldNotNullAndEmpty;
}
public List<KeyValue<String, RangeValue>> getRanges() {
if(ranges==null) {
this.ranges = new ArrayList<>();
}
return ranges;
}
public void setRanges(List<KeyValue<String, RangeValue>> ranges) {
this.ranges = ranges;
}
public Map<String, List<String>> getFilter() {
if(filter==null) {
this.filter = new HashMap<>();
}
return filter;
}
public void setFilter(Map<String, List<String>> filter) {
this.filter = filter;
}
public List<KeyValue<String, String>> getMatches() {
if(matches==null) {
this.matches = new ArrayList<>();
}
return matches;
}
public void setMatches(List<KeyValue<String, String>> matches) {
this.matches = matches;
}
public List<KeyValue<String, String>> getMatchesPartial() {
if(matchesPartial==null) {
this.matchesPartial = new ArrayList<>();
}
return matchesPartial;
}
public void setMatchesPartial(List<KeyValue<String, String>> matchesPartial) {
this.matchesPartial = matchesPartial;
}
public List<KeyValue<String, String>> getMatchesNot() {
if(matchesNot==null) {
this.matchesNot = new ArrayList<>();
}
return matchesNot;
}
public void setMatchesNot(List<KeyValue<String, String>> matchesNot) {
this.matchesNot = matchesNot;
}
}
As based on the structure of the code the matches, matchesPartial, matchesNot is nested under the filter Map, and each keyword queries should have key and value.
Now let's go back to the controller class, as you can see inside of the Response.success method
it is calling also the elasticSearchProductBslService.viewSortByFilterBy(searchBy) where inside of the searchBy it contains the request including the filterBy.
Let's jump to the viewSortByFilterBy() method inside of the elasticSearchProductBslService class.
public SearchByFilterByResponse viewSortByFilterBy(SearchByDto searchBy) throws IOException{
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
SearchRequest request = new SearchRequest();
request.indices("product_bsl");
request.source(sourceBuilder);
int fromIndex = searchBy.getPagination().getFrom();
int size = searchBy.getPagination().getSize();
elasticSearchHelper.buildFieldSort(searchBy, sourceBuilder);
sourceBuilder.from(fromIndex);
sourceBuilder.size(size);
BoolQueryBuilder queryBuilder = elasticSearchHelper.boolQueryBuilder(searchBy);
sourceBuilder.query(queryBuilder);
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
SearchHit[] searchHits = response.getHits().getHits();
SearchByFilterByResponse resp = new SearchByFilterByResponse();
resp.setTotalHits(response.getHits().getTotalHits().value);
List<ProductWithImage> products = searchHitToDto(searchHits);
resp.setProducts(products);
return resp;
}
Additional information for you, this is the DTO class for "product_bsl" index. As I will show it to you how it look like in the OpenAPI later.
ProductBslElasticDto class:
public class ProductBslElasticDto {
private String id;
private String name;
private List<OfferElasticDto> offers;
private List<ProductBslElasticCategory> productBslElasticCategory;
private String brandId;
private String brandName;
private String shortdesc;
private String longDesc;
private int brandRating;
private long dateInserted;
private List<String> imagePath;
private String isActive;
private List<String> images;
private List<String> imageId;
private long totalVisits;
private long totalVisitUpdateTime;
private long totalViewCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getShortdesc() {
return shortdesc;
}
public void setShortdesc(String shortdesc) {
this.shortdesc = shortdesc;
}
public String getLongDesc() {
return longDesc;
}
public void setLongDesc(String longDesc) {
this.longDesc = longDesc;
}
public int getBrandRating() {
return brandRating;
}
public void setBrandRating(int brandRating) {
this.brandRating = brandRating;
}
public String getBrandId() {
return brandId;
}
public void setBrandId(String brandId) {
this.brandId = brandId;
}
public long getDateInserted() {
return dateInserted;
}
public void setDateInserted(long dateInserted) {
this.dateInserted = dateInserted;
}
public List<ProductBslElasticCategory> getProductBslElasticCategory() {
return productBslElasticCategory;
}
public void setProductBslElasticCategory(List<ProductBslElasticCategory> productBslElasticCategory) {
this.productBslElasticCategory = productBslElasticCategory;
}
public long getTotalVisits() {
return totalVisits;
}
public void setTotalVisits(long totalVisits) {
this.totalVisits = totalVisits;
}
public long getTotalVisitUpdateTime() {
return totalVisitUpdateTime;
}
public void setTotalVisitUpdateTime(long totalVisitUpdateTime) {
this.totalVisitUpdateTime = totalVisitUpdateTime;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public List<String> getImages() {
return images;
}
public void setImages(List<String> images) {
this.images = images;
}
public List<String> getImageId() {
return imageId;
}
public void setImageId(List<String> imageId) {
this.imageId = imageId;
}
public List<OfferElasticDto> getOffers() {
return offers;
}
public void setOffers(List<OfferElasticDto> offers) {
this.offers = offers;
}
public long getTotalViewCount() {
return totalViewCount;
}
public void setTotalViewCount(long totalViewCount) {
this.totalViewCount = totalViewCount;
}
public List<String> getImagePath() {
return imagePath;
}
public void setImagePath(List<String> imagePath) {
sortIndexedImagePaths(imagePath);
this.imagePath = imagePath;
}
private void sortIndexedImagePaths(List<String> imagePaths) {
if (null == imagePaths) return;
for (String path : imagePaths) {
if (null == path ||
!PRODUCT_INDEXED_IMAGE_PATH_PATTERN.matcher(path).find()) {
return;
}
}
imagePaths.sort(String::compareTo);
}
}
Now after I show the DTO you can look back to the viewSortByFilterBy() again. I think you can disregard the SourceBuilder and SearchRequest let's focus on the elasticSearchHelper.boolQueryBuilder(searchBy) as we will jump inside of it.
ElasticSearchHelper class:
#Service
public class ElasticSearchHelper {
private static final String KEY_NAME = "name";
private static final String REGEX_SPACE = " ";
private static final String REGEX_WILDCARD = "*";
public BoolQueryBuilder boolQueryBuilder(SearchByDto searchBy) {
FilterBy filterBy = searchBy.getFilterBy();
BoolQueryBuilder rootBuilder = QueryBuilders.boolQuery();
if(filterBy!=null) {
nestedTermsQueryBuilder(rootBuilder, filterBy.getFilter());
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatches(), MUST);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesNot(), MUST_NOT);
nestedBoolQueryBuilder(rootBuilder, filterBy.getMatchesPartial(), SHOULD);
nestedExistsQueryBuilder(rootBuilder, filterBy.getDiscludeFieldNotNullAndEmpty());
nestedRangeQueryBuilder(rootBuilder, filterBy.getRanges());
}
return rootBuilder;
}
private void nestedTermsQueryBuilder(BoolQueryBuilder rootBuilder, Map<String, List<String>> filter) {
filter.forEach((key, value) -> {
TermsQueryBuilder nestedBuilder = QueryBuilders.termsQuery(key, value);
rootBuilder.must(nestedBuilder);
});
}
private void nestedBoolQueryBuilder(BoolQueryBuilder rootBuilder, List<KeyValue<String, String>> entries, ElasticSearchBoolQueryType queryType) {
if(entries != null && !entries.isEmpty()) {
Set<String> distinctKeys = entries.stream().map(KeyValue::getKey).collect(Collectors.toSet());
for (String key : distinctKeys) {
BoolQueryBuilder nestedBuilder = QueryBuilders.boolQuery();
for (KeyValue<String, String> entry : entries) {
nestedQueryStringOrDisMaxQueryBuilder(key, entry, nestedBuilder);
}
switch (queryType) {
case MUST:
rootBuilder.must(nestedBuilder);
break;
case MUST_NOT:
rootBuilder.mustNot(nestedBuilder);
break;
case SHOULD:
rootBuilder.should(nestedBuilder);
break;
default:
break;
}
}
}
}
I just included the boolQueryBuilder and nestedBoolQueryBuilder only just to focus relating to my concern. don't get confuse on the MUST, MUST_NOT, SHOULD it is the same for matches, matchesNot, matchesPartial as I have told earlier on the FilterBy class. So in this class I think the logic happens here, any suggestions for any changes and how should I improve search accuracy for this kind of structure?
How it looks like in OpenAPI as I will search for product name:
Request: POST "/bsl/view/products/sort-filter"
{
"pagination": {
"from": 0,
"size": 20
},
"sortBy": {
"fieldsAscOrDesc": {
"offers.financing.finalAmount": "desc"
}
},
"filterBy": {
"matches": [
{
"key": "name",
"value": "Lenovo IdeaPad3 81Y4001NPH"
}
],
"matchesNot": [
{
"key": "isActive",
"value": "false"
}
],
"discludeFieldNotNullAndEmpty": [
"offers"
]
}
}
Result was it had total of 17 hits and I used the matches keyword where it should be search the exact word right? But it shows different Lenovo products in the result.
Result
I have 3 classes: MainActivity, homePage and createPage; and a list List<Recipe> recipeList = new ArrayList<>() in MainActivity.
The user enters the homePage from the MainActivity. From homePage, the user can enter createPage and create a new recipe. This new recipe is intended to be passed back to MainActivity.
I've searched online and came across parcels. But when I tried, I get a NullPointerException.
Code for createPage where the list is passed on
ArrayList<Recipe> rList = new ArrayList<>();
Recipe r = new Recipe(...);
rList.add(r)
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
i.putExtras(b);
i.setClass(createPage.this, homePage.class);
startActivity(i);
Code for homePage where the list is received.
Is there something wrong with the getIntent()? Because when moving from MainActivity to homePage, it doesn't receive a bundle. Is this causing the error?
Intent intent = getIntent();
Bundle b = this.getIntent().getExtras();
if (b != null) {
Recipe r = b.getParcelable("recipe");
recipeList.add(r);
}
Code for Recipe class
public class Recipe implements Parcelable {
private String name;
private String description;
private String ingredients;
private int duration;
private String steps;
private int thumbnail;
protected Recipe(Parcel in) {
name = in.readString();
description = in.readString();
ingredients = in.readString();
duration = in.readInt();
steps = in.readString();
thumbnail = in.readInt();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIngredients() {
return ingredients;
}
public void setIngredients(String ingredients) {
this.ingredients = ingredients;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getSteps() { return steps; }
public void setSteps(String steps) { this.steps = steps; }
public int getThumbnail() { return thumbnail; }
public Recipe() {}
public Recipe(String name, int duration, String ingredients, String description, String steps, int thumbnail) {
this.name = name;
this.description = description;
this.ingredients = ingredients;
this.duration = duration;
this.steps = steps;
this.thumbnail = thumbnail;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeString(description);
parcel.writeString(ingredients);
parcel.writeInt(duration);
parcel.writeString(steps);
parcel.writeInt(thumbnail);
}
}
you are writing into Parcelable whole array under "recipe" key
b.putParcelableArrayList("recipe", (ArrayList<? extends Parcelable>) rList);
but on onther side you are looking not for list but for single Recipe item under same key
Recipe r = b.getParcelable("recipe");
you should use getParcelableArrayList or if you have only one Recipe for passing to another Activity just use putParcelable (not list)
Alternatively you can use serializable, that will be less complex.
For reference : https://stackoverflow.com/a/2736612/9502601
Eventhough parcellables are more faster but if you want a less complex solution then you can go for it.
For Comparison between Serializable and Parcelable.
https://stackoverflow.com/a/23647471/9502601
You can use this gson Lib for this
implementation 'com.google.code.gson:gson:2.8.9'
Send Data with Intent
Recipe r = new Recipe(...);
String recipeString = new Gson().toJson(r);
intent.putExtra("recipe",recipeString);
// For ArrayList
ArrayList<Recipe> recipeList = new ArrayList<>();
String recipeString = new Gson().toJson(recipeList);
intent.putExtra("recipeList",recipeString);
Receive Data From Intent
Recipe r = new Gson().fromJson(intent.getStringExtra("recipe"), Recipe.class);
// For Array List
Type listType = new TypeToken<ArrayList<Recipe>>(){}.getType();
ArrayList<Recipe> recipeList = new Gson().fromJson(intent.getStringExtra("recipeList"),listType);
I'm using Android Studio and I want to make a listview, which contains values that are received by JSON.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String JSONString = Handler.makeServiceCall(JSONUrl);
Log.e(TAG, "Response:" + JSONString);
if(JSONString != null){
try {
JSONObject CountriesJSONObject = new JSONObject(JSONString);
JSONArray Countries = CountriesJSONObject.getJSONArray("countries");
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i);
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
} catch (final JSONException e){
Log.e(TAG,e.getMessage());
ProgressDialog.setMessage("Error loading Data!");
}
}
return null;
}
This is the code for getting the JSON values, and i'm receiving an error
"No value for id"
What am I doing wrong?
You still have the "country" key to unwrap. Try like this:
for (int i = 1; i < Countries.length(); i++) {
JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");
//Details
String CountryID = Country.getString("id");
String CountryName = Country.getString("name");
String CountryImage = Country.getString("image");
//Hashmap
HashMap<String, String> TempCountry = new HashMap<>();
//Details to Hashmap
TempCountry.put("id", CountryID);
TempCountry.put("name", CountryName);
TempCountry.put("image", CountryImage);
//Hashmap to Countrylist
CountryList.add(TempCountry);
}
First step is to create a new Java class model for the JSON - you can just copy and paste this.
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
public class Countries {
public class CountriesList implements Serializable {
private Country[] countries;
public Country[] getCountries() {
return countries;
}
public void setCountries(Country[] countries) {
this.countries = countries;
}
public ArrayList<Country> getCountriesAsList() {
if(countries == null || countries.length == 0) {
return new ArrayList<>();
} else {
return (ArrayList<Country>) Arrays.asList(countries);
}
}
}
public class Country implements Serializable {
private String id;
private String name;
private String image;
public Country() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
}
Now, it's simply converting the JSON into Java object like this. You can use that ArrayList for adapter or however you like.
protected Void doInBackground(Void... voids) {
HttpHandler Handler = new HttpHandler();
String jsonString = Handler.makeServiceCall(JSONUrl);
Countries.CountriesList countries = new Gson().fromJson(jsonString, Countries.CountriesList.class);
// this is the full list of all your countries form json
ArrayList<Countries.Country> countryList = countries.getCountriesAsList();
}
Note: you will need the Gson library to use the solution I showed above. I use that to convert JSON into Java object.
compile 'com.google.code.gson:gson:2.8.0'
Ok... I now this is a silly question, but I am struggling with this.
public class University {
private List<Student> students;
public University() {
this.student = new ArrayList();
}
public void loadFile(String fileStudents) throws IOException {
BufferedReader readStudents = new BufferedReader(new FileReader(fileStudents));
while(true){
String line = readStudents.readLine();
if( line == null)
break;
String fields[] = line.split(":");
Student e = new Student(Long.parseLong(fields[0]),fields[1], fields[2]);
//System.out.println(e);
students.add(e);
}
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
I want to create a new method passing as a paramenter the object "e".
I want to return e.getNome();
The problem is the data type contained within the array is not known until runtime. I have created a test case to illustrate my problem. Everything works fine until it comes to arrays.
User user1 = new User(1, "one");
User user2 = new User(2, "two");
User [] users = {user1, user2};
Gson gson = new Gson();
// gson processing array of known a type. WORKS FINE
// observe use of brackets []
String toJson = gson.toJson(users, User[].class);
User [] newUsers = gson.fromJson(toJson, User[].class);
for(User user : newUsers) {
System.out.println(user.toString());
}
// gson processing using reflection for single user. WORKS FINE
final Class<?> userType = Class.forName("com.abc.ws.GsonTest$User");
User user3 = new User(3, "three");
toJson = gson.toJson(user3, userType);
Object newUser = gson.fromJson(toJson, userType);
System.out.println(newUser.toString());
// gson processing using reflection for array of users. FAILS.
toJson = gson.toJson(users, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
for(User user : newerUsers) {
System.out.println(user.toString());
}
btw: Below is the complete code.
package com.abc;
import com.google.gson.Gson;
public class GsonTest {
public static void main(String[] args) throws Exception {
GsonTest.go();
}
public static void go() throws Exception {
User user1 = new User(1, "one");
User user2 = new User(2, "two");
User [] users = {user1, user2};
Gson gson = new Gson();
// gson processing array of known a type. Works fine
// observe use of brackets []
String toJson = gson.toJson(users, User[].class);
User [] newUsers = gson.fromJson(toJson, User[].class);
for(User user : newUsers) {
System.out.println(user.toString());
}
// gson processing using reflection for single user. Works fine.
final Class<?> userType = Class.forName("com.abc.GsonTest$User");
User user3 = new User(3, "three");
toJson = gson.toJson(user3, userType);
Object newUser = gson.fromJson(toJson, userType);
System.out.println(newUser.toString());
// gson processing using reflection for array of users. Fails.
toJson = gson.toJson(users, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
Object newerUsers = gson.fromJson(toJson, WHAT_TO_PASS_HERE?); // it should be something like: userType[].class but that won't compile
for(User user : newerUsers) {
System.out.println(user.toString());
}
}
public static class User {
private int id;
private String name;
public User() { }
public User(int id, String name) {
this.id = id;
this.name = 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;
}
public String toString() {
return "id: " + this.id + ", name: " + this.name;
}
}
}
Try pass
Array.newInstance(userType, 0).getClass()
// serialized
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class Serialization {
private ArrayList<Student> obj;
public Serialization() {
obj = new ArrayList<Student>();
obj.add(new Student("qwrr", "qwerr", "qwerr"));
obj.add(new Student("zxcv", "zxcv", "zxcv"));
obj.add(new Student("asdf", "asdf", "asdf"));
}
public void Save() throws Exception{
FileOutputStream os = new FileOutputStream("cust.xml");
XMLEncoder encoder = new XMLEncoder(os);
encoder.writeObject(this.obj);
encoder.close();
}
#SuppressWarnings("unchecked")
public ArrayList<Student> Load() throws Exception{
FileInputStream os = new FileInputStream("cust.xml");
XMLDecoder decoder = new XMLDecoder(os);
ArrayList<Student> p = (ArrayList<Student>)decoder.readObject();
decoder.close();
return p;
}
public static void main(String[] args) throws Exception {
Serialization obj = new Serialization();
obj.Save();
ArrayList<Student> mas = obj.Load();
for(Student st:mas)
System.out.println(st);
}
}
// student
public class Student {
private String firstName;
private String lastName;
private String location;
public Student(){
}
public Student(String first,String last, String location) {
this.firstName = first;
this.lastName = last;
this.location = location;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setLocation(String location) {
this.location = location;
}
public String getLocation() {
return location;
}
#Override
public String toString(){
return this.firstName+" "+this.lastName+" "+this.location;
}
}
//