Search code examples
c#.netcouchbasecouchbase-view

parsing JSON object to a list of a model from couchbase view


I am trying to make a mapreduce view in couchbase like so. Right now my view code in couchbase server looks like this,

function(doc, meta)
{
  emit(doc.content,null);
}

where I am emitting the content of a document.

so when I iterate in (var rows in result.Rows), I want to assign each value in the content(in JSON) to a list of a model(abc) which has the get/set for serialNumber,uldNumber, and assignedDate in a class

row.key value has

{{
  "serialNumber": "1",
  "uldNumber": "33",
  "assignedDate": "2033-02-17T09:10:38"
}}

my class looks like

 public class abc
    {
        //[JsonProperty("serialNumber")]
        public string SerialNumber { get; set; }

        //[JsonProperty("uldNumber")]
        public string UldNumber { get; set; }

        //[JsonProperty("assignedDate")]
        public DateTime AssignedDate { get; set; }
    }

If I try to deserialize it like so,

 JsonSerializer js = new JsonSerializer();                       
 _abcList.Add(js.Deserialize<dynamic[]>(row));

I get "cannot convert from 'Couchbase.Views.ViewRow<dynamic>' to 'Newtonsoft.Json.JsonReader"

If i were to do this, row.Key.toString(); , I get exception error of 'Newtonsoft.Json.Linq.JObject'

"cannot convert couchbase.views.viewrow to string "

I have looked at this and this but both of these have not worked.


Solution

  • When you do an emit statement like this:

    emit(doc.content, null);
    

    You're just making the view key doc.content, and leaving the row data null. You might try this:

    emit(doc.content, doc);
    

    This will make the row content the full data in the document. Alternatively, you can use row.Id to get the document ID and use Read(row.Id) to read the document. This is slower, but uses less storage space for the view.

    Also, you typically don't put JSON object maps in the key. Normally it's either a single value like a number or string, or an array of values. Arrays are easier to use for view lookups.