What is the best way to deserialize Azure Search result to your own model?

Currently what I'm doing is serializing the JsonResult.Data then Deserialized into dynamic variable before looping in each row and get the Document. Is there any way to handle this? Thanks

            if (string.IsNullOrWhiteSpace(searchTerm_))
                searchTerm_ = "*";
            _azureSearch = new AzureSearchService("afindexdev");
            JsonResult result = new JsonResult
            {
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                Data = _azureSearch.SearchAssetFactory(searchTerm_).Results
            };

            string json = JsonConvert.SerializeObject(result.Data);
            var resultJsonString = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);

            foreach (dynamic row in resultJsonString)
            {
                var associatemItem = new AssociatedItem();
                associatemItem.Id = row.Document.Id;
                associatemItem.Title = row.Document.Title;
                associatemItem.Type = row.Document.Type;

                searcResult.AssociatedItems.Add(associatemItem);
            }

Answers


What about this?

var associatedItem = Newtonsoft.Json.JsonConvert.DeserializeObject< List < AssociatedItem > >(json);

That way you don't have to make your object yourself.


You can define your model with properties which you want to deserialize with attribute [SerializePropertyNamesAsCamelCase]. This attribute is included to Microsoft.Azure.Search library. After that, all you need to do is to define your model in search generic - like this Hotel class

var sp = new SearchParameters();

if (!String.IsNullOrEmpty(filter))
{
    sp.Filter = filter;
}

DocumentSearchResult<Hotel> response = indexClient.Documents.Search<Hotel>(searchText, sp);

You can find more info here


Need Your Help

How to check for version of app and request users to update?

objective-c ios version uialertview

How can I check if the user has the current version of my app and also pop up a message to request them to update their app version?