简体   繁体   中英

How to set multiple data types in one HashMap?

I am trying to set multiple values in hashmap in my android app. Some values are String and one value I want to send is an array of objects I created OnlineTestResultPOJO . Following is the code which I want to implement.

OnlineTestResultPOJO[] records = db.resultDao().getRecords();
HashMap<String, String> map = new HashMap<>();
map.put("dbname",dbname);
map.put("class",clas);
map.put("rollno",rollno);
map.put("access_token",accessToken);
map.put("records_arr", records);

Obviously it is giving error in the last line as it is not String , but is it possible to set all of these things in one HashMap ? I tried wrapping it with String.valueOf(records) , but that spoils the working of object producing unexpected results. Any alternate solution to achieve this?

Create map as below:

HashMap<String, Object> map = new HashMap<>();

Just declare your map like this:

HashMap<String, Object> map = new HashMap<>();

eg Object type for the value.

You can serialize Object to String and save it to HashMap as a String.

// serialize the object
 try {
     ByteArrayOutputStream bo = new ByteArrayOutputStream();
     ObjectOutputStream so = new ObjectOutputStream(bo);
     so.writeObject(myObject);
     so.flush();
     serializedObject = bo.toString();
 } catch (Exception e) {
     System.out.println(e);
 }

 // deserialize the object
 try {
     byte b[] = serializedObject.getBytes(); 
     ByteArrayInputStream bi = new ByteArrayInputStream(b);
     ObjectInputStream si = new ObjectInputStream(bi);
     MyObject obj = (MyObject) si.readObject();
 } catch (Exception e) {
     System.out.println(e);
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM