Search code examples
androidjsonrealminputstream

Realm android map date field using createObjectFromJson()


Started working on Realm database(Android), I am calling wcf service which response is as,

{
   "ProductId": 1,
  "ProductCategory": " CategorY_result",
  "ProductName": "Admission",
  "Priority": "High",
  "EnteredBy": null,
  "EnteredDate": "/Date(1224043200000)/",
}

and model for this as,

 public class Product extends RealmObject
 {
  @PrimaryKey
  private long ProductId;

  private String ProductCategory;
private String ProductName;
private String Typeofcollege;
private String Priority;
 private Date EnteredDate;    // is it mapped to Date directly ?
}

I want Date data type for EnteredDate field, i am doing steam parsing using createObjectFromJson() method

realm.createObjectFromJson(Product.class,inputStream);

but getting null value for EnteredDate. how can tackle this


Solution

  • WCF services supply Dates over JSON in a strange format, you have to format it by writing your own serialisation and deserialisations code (i.e. "/Date(12345678989+0000)/")

    Below in the code snippet I have defined how to write an object into Realm Db using Gson Lib to parse your WCF date format into java date format.

    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.text.TextUtils;
    import android.util.Log;
    
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    import com.google.gson.TypeAdapter;
    import com.google.gson.stream.JsonReader;
    import com.google.gson.stream.JsonToken;
    import com.google.gson.stream.JsonWriter;
    
    import java.io.IOException;
    import java.util.Date;
    
    import io.realm.Realm;
    import io.realm.RealmResults;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            // Initialize Realm
            Realm.init(this);
    
            // Get a Realm instance for this thread
            Realm realm = Realm.getDefaultInstance();
    
            //Gson instance for date matching
            Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new NetDateTimeAdapter()).create();
    
            //example of json you want to match
            String stringObj = "{\n" +
                    "      \"ProductId\": 1,\n" +
                    "      \"ProductCategory\": \" CategorY_result\",\n" +
                    "      \"ProductName\": \"Admission\",\n" +
                    "      \"Priority\": \"High\",\n" +
                    "      \"EnteredBy\": null,\n" +
                    "      \"EnteredDate\": \"/Date(1224043200000)/\"\n" +
                    "     }";
    
            //Using gson lib parsing json into gson into WcfObject
            Product object = gson.fromJson(stringObj, Product.class);
    
    
            //write the object into realm
            realm.beginTransaction();
            realm.insertOrUpdate(object);
            realm.commitTransaction();
    
            RealmResults<Product> result = realm.where(Product.class).findAll();
    
            for (Product obj : result) {
                //printing it to see weather it is working or not
                Log.e("value", obj.toString());
            }
    
        }
    
    
        private static class NetDateTimeAdapter extends TypeAdapter<Date> {
            @Override
            public Date read(JsonReader reader) throws IOException {
                if (reader.peek() == JsonToken.NULL) {
                    reader.nextNull();
                    return null;
                }
                Date result = null;
                String str = reader.nextString();
                str = str.replaceAll("[^0-9]", "");
                if (!TextUtils.isEmpty(str)) {
                    try {
                        result = new Date(Long.parseLong(str));
                    } catch (NumberFormatException e) {
                    }
                }
                return result;
            }
    
            @Override
            public void write(JsonWriter writer, Date value) throws IOException {
                // Nah..
            }
        }
    }
    

    Product class code

    import java.util.Date;
    
    import io.realm.RealmObject;
    import io.realm.annotations.PrimaryKey;
    
    public class Product extends RealmObject {
            @PrimaryKey
            private int ProductId;
            private String ProductCategory;
            private String ProductName;
            private String EnteredBy;
            private Date EnteredDate;
    
            @Override
            public String toString() {
                    return "WcfObject{" +
                            "ProductId=" + ProductId +
                            ", ProductCategory='" + ProductCategory + '\'' +
                            ", ProductName='" + ProductName + '\'' +
                            ", EnteredBy='" + EnteredBy + '\'' +
                            ", EnteredDate=" + EnteredDate.toString() +
                            '}';
            }
    }
    

    All the above given code is described with the comment. Let me know if any clarification is needed.