Realm android 使用 createObjectFromJson() 映射日期字段
Realm android map date field using createObjectFromJson()
开始处理 Realm 数据库(Android),我正在调用 wcf 服务,其响应如下,
{
"ProductId": 1,
"ProductCategory": " CategorY_result",
"ProductName": "Admission",
"Priority": "High",
"EnteredBy": null,
"EnteredDate": "/Date(1224043200000)/",
}
并以此为模型,
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 ?
}
我想要 EnteredDate 字段的日期数据类型,我正在使用
createObjectFromJson() 方法
realm.createObjectFromJson(Product.class,inputStream);
但 EnteredDate 的值为空。如何解决这个问题
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)/")
在下面的代码片段中,我定义了如何使用 Gson Lib 将对象写入 Realm Db 以将 WCF 日期格式解析为 java 日期格式.
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..
}
}
}
产品class代码
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() +
'}';
}
}
上面给出的所有代码都用注释进行了描述。如果需要任何说明,请告诉我。
开始处理 Realm 数据库(Android),我正在调用 wcf 服务,其响应如下,
{
"ProductId": 1,
"ProductCategory": " CategorY_result",
"ProductName": "Admission",
"Priority": "High",
"EnteredBy": null,
"EnteredDate": "/Date(1224043200000)/",
}
并以此为模型,
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 ?
}
我想要 EnteredDate 字段的日期数据类型,我正在使用 createObjectFromJson() 方法
realm.createObjectFromJson(Product.class,inputStream);
但 EnteredDate 的值为空。如何解决这个问题
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)/")
在下面的代码片段中,我定义了如何使用 Gson Lib 将对象写入 Realm Db 以将 WCF 日期格式解析为 java 日期格式.
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..
}
}
}
产品class代码
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() +
'}';
}
}
上面给出的所有代码都用注释进行了描述。如果需要任何说明,请告诉我。