package cn.myapps.runtime.common.servlet.view;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.io.IOException;
import java.io.OutputStream;

public class MultiLanguageMappingJsonView extends MappingJackson2JsonView {

    @Override
    protected void writeContent(OutputStream stream, Object object) throws IOException {
        JsonGenerator generator = this.getObjectMapper().getFactory().createGenerator(stream, this.getEncoding());
        this.writePrefix(generator, object);
        Class<?> serializationView = null;
        FilterProvider filters = null;
        Object value = object;
        if (object instanceof MappingJacksonValue) {
            MappingJacksonValue container = (MappingJacksonValue)object;
            value = container.getValue();
            serializationView = container.getSerializationView();
            filters = container.getFilters();
        }

        if (serializationView != null) {
            this.getObjectMapper().writerWithView(serializationView).writeValue(generator, value);
        } else if (filters != null) {
            this.getObjectMapper().writer(filters).writeValue(generator, value);
        } else {
            this.getObjectMapper().writeValue(generator, value);
        }

        this.writeSuffix(generator, object);
        generator.flush();
    }
}
