14

spring MVC で REST Web サービスを開発しています。jackson 2 が mongodb オブジェクト ID をシリアル化する方法を変更する必要があります。jackson 2 の部分的なドキュメントを見つけたので、何をすべきかわかりません。私がしたことは、カスタムシリアライザーを作成することでした:

public class ObjectIdSerializer extends JsonSerializer<ObjectId> {


    @Override
    public void serialize(ObjectId value, JsonGenerator jsonGen,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {
        jsonGen.writeString(value.toString());
    }
}

ObjectMapper を作成する

public class CustomObjectMapper extends ObjectMapper {

    public CustomObjectMapper() {
        SimpleModule module = new SimpleModule("ObjectIdmodule");
        module.addSerializer(ObjectId.class, new ObjectIdSerializer());
        this.registerModule(module);
    }

}

次に、マッパーを登録します

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="my.package.CustomObjectMapper"></bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

私の CustomConverter は呼び出されません。CustomObjectMapper の定義が間違っていると思います。jackson 1.x のコードから適応させました。

私のコントローラーでは、@ResponseBody を使用しています。私はどこで間違っていますか?ありがとう

4

3 に答える 3

3

対応するモデル フィールドに@JsonSerializeアノテーションを付ける必要があります。あなたの場合、次のようになります。

public class MyMongoModel{
   @JsonSerialize(using=ObjectIdSerializer.class)
   private ObjectId id;
}

しかし、私の意見では、エンティティ モデルを VO として使用しない方がよいでしょう。より良い方法は、異なるモデルを持ち、それらの間をマッピングすることです。サンプル プロジェクトはこちらにあります (例として、Spring 3 と Jackson 2 で日付のシリアル化を使用しました)。

于 2015-01-25T12:37:35.570 に答える
0

これを行う方法は次のとおりです。

カスタム シリアライザーを宣言するアノテーションを作成します。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyMessageConverter{
}

mvcconfiguration ファイルで、これに対するコンポーネント スキャンを設定します。

<context:include-filter expression="package.package.MyMessageConverter"
            type="annotation" />

を実装するクラスを作成しますHttpMessageConverter<T>

@MyMessageConverter
public MyConverter implements HttpMessageConverter<T>{
//do everything that's required for conversion.
}

というクラスを作成しますextends AnnotationMethodHandlerAdapter implements InitializingBean

    public MyAnnotationHandler extends AnnotationMethodHandlerAdapter implements InitializingBean{
    //Do the stuffs you need to configure the converters
    //Scan for your beans that have your specific annotation
    //get the list of already registered message converters
    //I think the list may be immutable. So, create a new list, including all of the currently configured message converters and add your own. 
    //Then, set the list back into the "setMessageConverters" method.
    }

これがあなたの目標に必要なすべてだと思います。

乾杯。

于 2013-01-16T18:06:14.623 に答える