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

如何让FasterXml ObjectMapper为long类型字段生成带format属性的Schema

解决方案

方法一:用Jackson JsonSchema注解标记字段

直接在需要添加format的属性上使用@JsonSchema注解指定格式值,无需修改业务逻辑代码:

@Data
public static class MyClass {
    private int myInt;
    // 为long类型属性指定format为int64
    @JsonSchema(format = "int64")
    private long myLong;
}

重新运行测试代码,生成的Schema中myLong属性会自动带上"format": "int64"字段。

方法二:不修改实体类,通过代码修改生成的Schema

如果不想改动实体类,可以在Schema生成后手动调整,或者自定义访问器自动处理:

方式1:生成Schema后手动修改属性

@SneakyThrows
@Test
public void test() {
    ObjectMapper objectMapper = new ObjectMapper();
    SchemaFactoryWrapper schemaVisitor = new SchemaFactoryWrapper();
    objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(MyClass.class), schemaVisitor);
    
    // 取出Schema对象,修改指定属性的format
    ObjectSchema schema = (ObjectSchema) schemaVisitor.finalSchema();
    NumberSchema longPropertySchema = (NumberSchema) schema.getProperties().get("myLong");
    longPropertySchema.setFormat("int64");
    
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema));
}

方式2:自定义Schema访问器自动处理long类型

继承SchemaFactoryWrapper,重写long类型的访问逻辑,自动添加format:

public class CustomSchemaFactoryWrapper extends SchemaFactoryWrapper {
    @Override
    public JsonFormatVisitorForLong visitLongFormat(LongType type) {
        return new JsonFormatVisitorForLong.Base() {
            @Override
            public void numberSchema(NumberSchema schema) {
                schema.setFormat("int64");
                _context.addSchema(schema);
            }
        };
    }
}

测试时替换为自定义访问器:

@SneakyThrows
@Test
public void test() {
    ObjectMapper objectMapper = new ObjectMapper();
    CustomSchemaFactoryWrapper schemaVisitor = new CustomSchemaFactoryWrapper();
    objectMapper.acceptJsonFormatVisitor(objectMapper.constructType(MyClass.class), schemaVisitor);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schemaVisitor.finalSchema()));
}

最终生成的Schema示例

无论使用哪种方法,最终输出的Schema都会包含预期的format字段:

{
   "type":"object",
   "id":"urn:jsonschema:........:MyClass",
   "properties":{
      "myInt":{
         "type":"integer"
      },
      "myLong":{
         "type":"integer",
         "format":"int64"
      }
   }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:00:41