【问题标题】:What is the best way to deserialize Azure Search result to your own model?将 Azure 搜索结果反序列化为您自己的模型的最佳方法是什么?
【发布时间】:2016-04-20 12:32:42
【问题描述】:

目前我正在做的是将JsonResult.Data 序列化,然后反序列化为dynamic 变量,然后在每一行中循环并获取Document。有没有办法处理这个?谢谢

            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);
            }

【问题讨论】:

  • 你能详细说明一下这个问题吗?不清楚您是在询问第 3 方 Azure 搜索客户端还是一般场景。我不认识你用来调用 Azure 搜索的代码。您是否尝试过官方的 .NET SDK? nuget.org/packages/Microsoft.Azure.Search
  • @BruceJohnston:我在“AzureSearchService”中调用 Azure 搜索,但这不是我的问题。我已经拥有来自 azure 的数据并存储在“结果”变量中,我的问题是在这种情况下反序列化结果的最佳方法是什么。
  • 为什么需要反序列化 .NET 代码的结果?当您从 SearchAssetFactory 取回它们时,它们不是已经反序列化了吗?通常,当我看到像这样创建 JsonResult 的代码时,它是为了将搜索结果发送回浏览器。您的总体情况是什么?

标签: c# asp.net json deserialization azure-cognitive-search


【解决方案1】:

这个怎么样?

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

这样您就不必自己制作对象了。

【讨论】:

    【解决方案2】:

    您可以使用属性 [SerializePropertyNamesAsCamelCase] 来定义您想要反序列化的属性的模型。此属性包含在 Microsoft.Azure.Search 库中。之后,您需要做的就是在搜索泛型中定义您的模型——比如这个 Hotel 类

    var sp = new SearchParameters();
    
    if (!String.IsNullOrEmpty(filter))
    {
        sp.Filter = filter;
    }
    
    DocumentSearchResult<Hotel> response = indexClient.Documents.Search<Hotel>(searchText, sp);
    

    您可以找到更多信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-14
      • 2010-11-06
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2019-06-01
      • 1970-01-01
      • 2010-11-06
      相关资源
      最近更新 更多