c# - 嵌套版本 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) 以正确反序列化。
解决方案
响应正文中总部分的架构在弹性搜索的6.x和7.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()
}
};
希望有帮助。
推荐阅读
- sql - 在 sql server 中查找缺少的组条目
- swift - 将 MKAnnotation 添加到 MKMapView 上方的位置,而不是在中心
- swift - Swift 允许声明变量名与参数名或函数名相同
- objective-c - 当dispatch_source_t是定时器时,为什么不是主线程时线程一直在变化?
- javascript - JQuery DatePicker 多月生成
- php - PHP将会话值回显到新会话?
- flutter - VSCode 上的错误:无法确定捆绑的 Java 版本
- jasper-reports - 关于修改 pdf 输出内容的权限
- c - 当 main() 函数被回调时,程序终止。有没有办法解决这个问题?
- javascript - 一个关于“this”关键字的简单 JS 问题