Android Develeoper
Android Develeoper

Reputation: 421

How to convert String value to Custom Model Object in Java?

I have one Model Object. In which, i have multiple values. I want to store this Values in SQLite. But data is large, so i want to store Direct Model object in databse. So i convert model Object to string and store it into database.

Now, Problem is that how to convert this String value to Model Object. If you have any idea, please share that with Me.

For example,

Person p = new Person();
p.setname("xyz");
p.setage("18");`

String person=p.toString();

Now How to get this "person" string back to Person "p" model object.

This is my code.

ContentValues values = new ContentValues();
    String favorite_id = UUID.randomUUID().toString();
    values.put(EMuseumLocalData.KEY_FAVORITE_EXHIBITS_ID, favorite_id);
    values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_ID, Integer.parseInt(categoryByCustomerList.get(position).getSubCategoryItemID()));
    try {
        Gson gson = new Gson();
        String personString = gson.toJson(getAllCategory.get(position).toString());
        values.put(EMuseumLocalData.KEY_EXHIBIT_SUBCATEGORY_ITEM_DATA, personString);

        Gson gson1 = new Gson();
        CategoryByCustomer categoryByCustomer = gson1.fromJson(personString, categoryByCustomer.getName());
    } catch (JSONException e) {
        e.printStackTrace();
    }

Upvotes: 13

Views: 29182

Answers (3)

user6077173
user6077173

Reputation:

Consider using a json string representation of the Model Object. There are many java libraries like Jackson, Gson etc., available to help you with serialization/deserialization part.

Here's a sample code to do this in Jackson

//For conversion of Person object(person) to json String:

String personJsonString = new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(person);


//For conversion of json String back to Person object(person)

Person person = new com.fasterxml.jackson.databind.ObjectMapper().readValue(personJsonString, Person.class);

Upvotes: 1

Pankaj Kumar
Pankaj Kumar

Reputation: 82978

You should use GSON or similar libs for this.


Store to DB

For example If you use GSON

Person p = new Person();
p.setname("xyz");
p.setage("18");
Gson gson = new Gson();
String personString = gson.toJson(p);

Now store this personString to DB.


Read from DB

Get back this object from database, read string from DB and convert it to object like below

String personStringFromDB = READ_LOGIC_OF_DB;
Gson gson = new Gson();
Person p = gson.fromJson(personStringFromDB, Person.class);

For more information, read GSON - Gson Example

Upvotes: 22

Mark Shen
Mark Shen

Reputation: 346

You can make Model Object serializable. You need to store the serialized object in SQLite. When you need it, you just get that serialized object from SOLite and deserialize it.

Upvotes: 0

Related Questions