Couchbase Lite resultset to object in C#?

Ok , I thought I would just show how I have accomplished this - so if others search for it then you may be able to use the same approach…

First, I spent the day working with reflection - identifying datatypes, arrays, classes inside my class etc. etc. - quite tedious.

The problem really was that I could not get a JSON representation of my data from the database. So at some point I got my hands on an ordinary Dictionary<string,object> as opposed to the Couchbase LIte DictonaryObject as that was the only way I could find to use the same code for deserializing a JsonDocument and a Dictionary from a query resultset.

And then at a point the idea came to see if I could serialize/deserialize an ordinary Dictionary - and yes you can! Therefore, I replaced my relatively complex code with this:

private T deserialize(Dictionary<string, object> data)
{
   var json = JsonConvert.SerializeObject(data, Formatting.Indented);
   return JsonConvert.DeserializeObject<T>(json);
}

Voilá!

And this method I can call from traversing the query result set:

var result = query.Execute();
foreach (var record in result.AllResults())
{
    var data = record.GetDictionary(dataStore.Db.Name);
    list.Add(deserialize(data.ToDictionary()));
}

as well as from a document found directly by id:

var record = dataStore.Db.GetDocument(id);
var obj = deserialize(record.ToDictionary());

There may be better ways to do this (y0u could share your solution/comments here) - and really it should be part of the SDK.

I’ll mark this as a solution to make it easier for others to find :slight_smile: