You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义SchemaResolver实现后resolve函数未被调用的问题排查

自定义SchemaResolver的resolve未调用的原因及解决方案

核心原因:resolve方法仅在解析外部$ref引用时触发

你的resolve函数没被调用,大概率是因为当前加载的主schema中没有需要跨文件/跨URL解析的$ref引用。SchemaResolver的设计目的是处理外部引用的解析逻辑,比如当schema里出现"$ref": "./other_schema.json"或者"$ref": "http://example.com/schema.json"这类需要加载外部资源的引用时,才会触发resolve方法。如果主schema里只有本地片段引用(比如"$ref": "#/definitions/foo"),或者完全没有$ref,resolver根本不会被调用。

另外,你想修改根schema的$id,这个逻辑不该放在resolve里——根schema的$id是直接从加载的JSON中读取的,不会经过resolver的处理流程。

修复步骤

  1. 添加外部引用触发resolver
    在你的schemas/schema.json中添加一个指向其他schema文件的引用,比如:

    {
      "$id": "original-id",
      "$ref": "./user_schema.json"
    }
    

    这样编译时就会触发resolver去解析这个外部引用,你的resolve函数就会被调用。

  2. 直接修改根schema的$id
    如果要修改根schema的$id,不需要通过resolver,加载后直接修改即可:

    let mut schema = serde_json::from_str(&json)?;
    // 直接修改根schema的$id
    schema["$id"] = "file:///Users/maryam/projects/play-rust/json_schema/schemas".to_string().into();
    
  3. 确认库的行为符合预期
    如果你使用的是json-schema crate,SchemaResolver的resolve方法确实只负责解析外部引用的内容,根schema的初始化流程不会调用该方法,这是库的设计逻辑。

测试验证

修改后重新运行代码,当主schema包含外部$ref时,你应该能看到resolve里的日志和打印信息输出。


内容的提问来源于stack exchange,提问作者Maryam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:30:05