There is some problem, how to convert key-value pair type string data into Map of the class object?
Scenario- when we want to send a request object that has key-value pair property, Data comes from the .txt file, data base, or any resources that have key value pairs data. By using the GSON Library we can do it.
What is GSON?
Gson is a Java library that can be used to parse the Java Objects into their JSON and vice-versa. It can also be used to convert a JSON string to an equivalent Java object. It is developed by the Google. for more about GSON click the link https://mobikul.com/introduction-gson-use/
So how we will solve?
Just we use the TokenType<T> generic class from com.google.gson.reflect package of GSON. TokenType class has property, Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.
Here is my example, I am getting data from SQLite Database in my android application, and forces to convert key-value pair string into HashMap by using the gson.fromJson() method of GSON object, just passes the type object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
private void parseData(Cursor cursor, OfflineDataBaseHandler offlineDataBaseHandler ){ OfflineCartRequestData offlineCartRequestData = new OfflineCartRequestData(); List<AddToCartRequest> cartList = new ArrayList<AddToCartRequest>(); try { // use for converting Dynomic TYPE for JSON Object. Gson gson = new Gson(); Type type = new TypeToken<Map<String, String>>(){}.getType(); cursor.moveToFirst(); do{ AddToCartRequest cartRequest = new AddToCartRequest(); ProductData request = new ProductData(); request.setAmount(cursor.getInt(cursor.getColumnIndex("amount"))+""); request.setProductId(cursor.getString(cursor.getColumnIndex("productId"))); request.setExtra((Map<String, String>) gson.fromJson(cursor.getString(cursor.getColumnIndex("extra")), type)); request.setProductOptions((Map<String, String>) gson.fromJson(cursor.getString(cursor.getColumnIndex("productOption")), type)); cartRequest.setProductData(request); cartList.add(cartRequest); }while(cursor.moveToNext()); offlineCartRequestData.setOfflineCArtData(cartList); offlineCartRequestData.setUrserId(AppSharedPref.getCustomerId(Cart.this)); addToOfflineCart(offlineDataBaseHandler, offlineCartRequestData); }catch (SQLException e){ cursor.close(); offlineDataBaseHandler.close(); e.printStackTrace(); } } |
References:-https://github.com/google/gson/blob/main/gson/src/main/java/com/google/gson/reflect/TypeToken.java