首页 > 解决方案 > 嵌套版本 6.x 中的 InMemoryConnection Elasticsearch jsonSerializationException

问题描述

使用 NEST 6.x 版和 NEST.JSonSerializer 6.x 版,我收到 JSONSerialization 异常,使用 inMemory elasticsearch 进行单元测试。

我尝试使用 Nest 和 JsonSersializer 版本 7.x,它运行良好。但是我的生产服务器有 6.x 版本,所以我需要在 6.x NEST Client 上运行测试。

    var response = new
    {
        took = 1,
        timed_out = false,
        _shards = new
            {
                total = 2,
                successful = 2,
                failed = 0
            },
                hits = new
                {
                    total = new { value = 25 },
                    max_score = 1.0,
                    hits = Enumerable.Range(1, 25).Select(i => (object)new
                    {
                        _index = "project",
                        _type = "project",
                        _id = $"Project {i}",
                        _score = 1.0,
                        _source = new { name = $"Project {i}" }
                    }).ToArray()
                    }
     };

    var responseBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response));
    var connection = new InMemoryConnection(responseBytes, 200);
    var connectionPool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var settings = new ConnectionSettings(connectionPool,connection).DefaultIndex("project");
        settings.DisableDirectStreaming();
    var client = new ElasticClient(settings);
    var searchResponse = client.Search<Project>(s => s.MatchAll());

预期输出:来自 inMemory elasticsearch 的响应出现 错误: JsonSerializationException:无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型“System.Int64”,因为该类型需要 JSON 原始值(例如字符串、数字, boolean, null) 以正确反序列化。

标签: c#elasticsearchnest

解决方案


响应正文中总部分的架构在弹性搜索的6.x7.x版本之间发生了变化。如果您想让您的响应主体与 NEST 6.x 一起使用,您需要将总部分从

..
total = new { value = 25 },
..

..
total = 25,
..

完整示例:

var response = new
{
    took = 1,
    timed_out = false,
    _shards = new
    {
        total = 2,
        successful = 2,
        failed = 0
    },
    hits = new
    {
        total = 25,
        max_score = 1.0,
        hits = Enumerable.Range(1, 25).Select(i => (object)new
        {
            _index = "project",
            _type = "project",
            _id = $"Project {i}",
            _score = 1.0,
            _source = new { name = $"Project {i}" }
        }).ToArray()
    }
};

希望有帮助。


推荐阅读