realm-java icon indicating copy to clipboard operation
realm-java copied to clipboard

How to convert realmobject to JSON

Open youguobin opened this issue 4 years ago • 1 comments

My requirement is to convert the information stored in realm into JSON, which can also be converted into realm data.

Based on the above requirements, I can use that RealmResult.asJson Method to convert the data into a JSON string. The attempt to transfer out was successful. But the transferred JSON will be transferred out through realm.createAllFromJson There was an exception when reading. The exception information is below:

io.realm.exceptions.RealmException: Failed to parse date ["2020-03-29 22:24:01']: Invalid time zone indicator ' '
    at io.realm.internal.android.JsonUtils.stringToDate(JsonUtils.java:72)

The problem is that realmobject has a date data and there seems to be no time zone information when it is transferred out. I don't know how to deal with this problem.

youguobin avatar Feb 26 '21 03:02 youguobin

I was able to reproduce this. I will try to come up with the best fix without breaking existing behavour. I don't think that I have an easy workaround for this while waiting for the fix, so the immediate one would be to add the Z timezone to all timestamps with something like (fixed previously erroneous suggestion):

String fixed = json.replaceAll("(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2})", "$1T$2Z");

rorbech avatar Feb 26 '21 10:02 rorbech