【问题标题】:InMemoryConnection Elasticsearch jsonSerializationException in nest version 6.x嵌套版本 6.x 中的 InMemoryConnection Elasticsearch jsonSerializationException
【发布时间】:2019-09-16 15:41:48
【问题描述】:

使用 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 原始值(例如字符串、数字、布尔值、null)才能正确反序列化。

【问题讨论】:

    标签: c# elasticsearch nest


    【解决方案1】:

    响应正文中总部分的架构在弹性搜索的 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()
        }
    };
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢(y)...它对我有用...现在我可以毫无例外地获取数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2019-10-08
    相关资源
    最近更新 更多