Search code examples
c#jsonserializationxamarin.iosrealm

How can I serialize a RealmObject to JSON in Realm for Xamarin?


I need to serialize a deeply nested RealmObject to JSON for posting to a web api, using Xamarin with C#.

The reason for this is because I don't want the RealmObject properties to carry over, so really I'm looking for a POCO representation that I can serialize to JSON. I can't find any helper method in Realm for Xamarin to do this, so I'm guessing I need to roll my own.

I am considering a few options and was hoping for some feedback:

  1. Use a JSON.NET Custom ContractResolver.
  2. Including a ToObject method on the RealmObject that returns a dynamic type which I can then serialize using JsonConvert.SerializeObject
  3. Using JsonTextWriter to iterate over the object and manually create the corresponding json.

At the moment I'm looking at option 2, as it's very straight forward e.g.

public class Person:RealmObject {
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public IList<Dog> Dogs {get;set;}

    public dynamic ToObject(){
        return new {FirstName,LastName, Dogs = Dogs.Select(x => x.ToObject())};
  }
}

public class Dog {
    public string Name;

    public dynamic ToObject(){
      return new {Name};
    }
}

var person = new Person(){...}
var json = JsonConvert.SerializeObject(person.ToObject());
var content = new StringContent(json);
var response = await client.PostAsync(url, content);

Any thoughts?


Solution

  • If you don't mind applying a few attributes, a cleaner (in my mind) solution would be to use the JsonObject attribute with MemberSerialization.OptIn argument:

    [JsonObject(MemberSerialization.OptIn)] // Only properties marked [JsonProperty] will be serialized
    public class Person : RealmObject
    {
        [JsonProperty]
        public string FirstName { get; set; }
    
        [JsonProperty]
        public string LastName { get; set; }
    
        [JsonProperty]
        public IList<Dog> Dogs { get; set; }
    }