Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Jackson从多个模块中选择注册模块以将JSON序列化为字符串?_Java_Json_Serialization_Jackson - Fatal编程技术网

Java Jackson从多个模块中选择注册模块以将JSON序列化为字符串?

Java Jackson从多个模块中选择注册模块以将JSON序列化为字符串?,java,json,serialization,jackson,Java,Json,Serialization,Jackson,我有一个简单的java类,希望将其序列化为不同的JSON输出。e、 g: Class User { public int id; public String name; } // 2 expected outputs Version 1 (V1): {"id": "1", "first_name": "A"} Version 2 (V2): {"id": "1", "name": "A"} 我创建了两个自定义模块来写入JSON字符串,它们注册到一个ObjectMappe

我有一个简单的java类,希望将其序列化为不同的JSON输出。e、 g:

Class User {
    public int id; 
    public String name;
} 

// 2 expected outputs
Version 1 (V1): {"id": "1", "first_name": "A"} 
Version 2 (V2): {"id": "1", "name": "A"}
我创建了两个自定义模块来写入JSON字符串,它们注册到一个ObjectMapper,如下所示:

public class ItemSerializerModuleV1 extends SimpleModule {

    public ItemSerializerModuleV1() {
        super(NAME, VERSION_UTIL.version());
        addSerializer(Item.class, new ItemSerializerV1());
    }
}

public class ItemSerializerModuleV2 extends SimpleModule {

    public ItemSerializerModuleV2() {
        super(NAME, VERSION_UTIL.version());
        addSerializer(Item.class, new ItemSerializerV2());
    }
}

ObjectMapper mapper = new ObjectMapper();
mapper.registerModules(new ItemSerializerModuleV1(), new ItemSerializerModuleV2());
然而,当ObjectMapper写入JSON字符串时,我不知道如何选择它应该使用哪个模块。它只选择具有下面代码的V2模块(最后注册的模块),而我也希望编写为V1

String serialized = mapper.writeValueAsString(myItem);

模块可用于扩展
ObjectMapper
提供的功能,例如,通过添加自定义序列化程序和反序列化程序的提供程序。您不能为特定序列化选择模块,也不能在模块注册后禁用该模块


因此,您应该有两个
ObjectMapper
实例,每个实例都将注册一个不同的模块。

是的,我可以用最简单的方法来注册,但是,不确定registerModules()方法的用途。我想,它可以注册模块并选择一个模块作为JSON字符串写入。@BằngRikimaru模块可用于扩展
ObjectMapper
提供的功能,例如,通过添加自定义序列化程序和反序列化程序的提供程序。您不能为特定序列化选择模块,也不能在模块注册后禁用该模块。