如何在 Spring Boot 应用程序中使用 JSON 处理器而不是 jackson 或 gson?

发布于 2025-01-17 02:44:26 字数 593 浏览 1 评论 0原文

我想在我的 Spring Boot 应用程序中使用像 Genson 这样的 JSON 处理器。

当您使用 Jackson 或 Gson 时,由于这两个库的 Spring Boot 自动配置,您会感到非常舒服。

在此链接中,有是用 Gson 替换 Jackson 的绝佳指南。

为了解决我的问题,我创建了 genson 和 gensonBuilder bean 但是我应该怎么做才能将这一行添加到我的配置中? spring.http.converters.preferred-json-mapper=genson

除了上述之外,我还需要执行其他操作来用 Genson 库替换 Jackson 吗?

I want to use a JSON processor like Genson in my spring boot application.

When you use Jackson or Gson you are so comfortable due to the spring boot auto-configuration for these two libraries.

In this link, there is a great guide for replacing Jackson with Gson.

For solving my problem, I created the genson and gensonBuilder bean But what should I do to be able to add this line to my config? spring.http.converters.preferred-json-mapper=genson

Do I need to do anything other than the above for replacing Jackson with Genson library?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

無處可尋 2025-01-24 02:44:27

Spring Boot 有一个指南:

<强>1。首先,从 Spring Boot 应用程序中排除 JACKSON

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Exclude the default Jackson dependency -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2。注册转换器和Genson类

Genson 有 Spring 的 HTTP 转换器 com.owlike.genson.ext.spring.GensonMessageConverter来源< /a>.
如果 Spring Boot 应用程序只需使用此转换器创建新 bean。它将自动应用。

请参阅
在 Spring Boot 中注册自定义 MessageConverter

文档

上下文中存在的任何 HttpMessageConverter bean 都将被
添加到转换器列表

    @Bean
    public Genson genson() {
        return new GensonBuilder().setHtmlSafe(true).setSkipNull(true).useBeanViews(true).create();
    }

    @Bean
    public com.owlike.genson.ext.spring.GensonMessageConverter gensonMessageConverter() {
        return new com.owlike.genson.ext.spring.GensonMessageConverter(genson());
    }

spring.http.converters.preferred-json-mapper=genson 不是必需的,只需删除此配置即可。

There is a guide for Spring Boot:

1. First of all exclude JACKSON from your Spring Boot application

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- Exclude the default Jackson dependency -->
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-json</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

2. Register converter and Genson class

Genson has HTTP converter for Spring com.owlike.genson.ext.spring.GensonMessageConverter, Sources.
In case Spring Boot application just create new bean with this converter. It will be applied automatically.

See Registering a custom MessageConverter in Spring Boot

Documentation

Any HttpMessageConverter bean that is present in the context will be
added to the list of converters

    @Bean
    public Genson genson() {
        return new GensonBuilder().setHtmlSafe(true).setSkipNull(true).useBeanViews(true).create();
    }

    @Bean
    public com.owlike.genson.ext.spring.GensonMessageConverter gensonMessageConverter() {
        return new com.owlike.genson.ext.spring.GensonMessageConverter(genson());
    }

spring.http.converters.preferred-json-mapper=genson is not required, just remove this config.

指尖微凉心微凉 2025-01-24 02:44:27

要使用默认情况下 Spring 不支持的自定义转换库,您需要实现自己的 AbstractJsonHttpMessageConverter

import com.owlike.genson.Genson;
import com.owlike.genson.GensonBuilder;
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;

public class GensonHttpMessageConverter extends AbstractJsonHttpMessageConverter {

    private Genson genson;

    public GensonHttpMessageConverter() {
        this(new GensonBuilder()
                .useIndentation(true)
                .create());
    }

    public GensonHttpMessageConverter(Genson genson) {
        Assert.notNull(genson, "A Genson instance is required");
        this.genson = genson;
    }

    public void setGenson(Genson genson) {
        Assert.notNull(genson, "A Genson instance is required");
        this.genson = genson;
    }

    public Genson getGenson() {
        return this.genson;
    }

    @Override
    protected Object readInternal(Type resolvedType, Reader reader) {
        return getGenson().deserializeInto(reader, resolvedType);
    }

    @Override
    protected void writeInternal(Object object, @Nullable Type type, Writer writer) {
        getGenson().serialize(object, writer);
    }
}

之后您需要注册它:

import com.example.genson.GensonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new GensonHttpMessageConverter());
    }
}

另请参阅:

To use custom, not supported by default by Spring conversion library you need to implement your own AbstractJsonHttpMessageConverter:

import com.owlike.genson.Genson;
import com.owlike.genson.GensonBuilder;
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Type;

public class GensonHttpMessageConverter extends AbstractJsonHttpMessageConverter {

    private Genson genson;

    public GensonHttpMessageConverter() {
        this(new GensonBuilder()
                .useIndentation(true)
                .create());
    }

    public GensonHttpMessageConverter(Genson genson) {
        Assert.notNull(genson, "A Genson instance is required");
        this.genson = genson;
    }

    public void setGenson(Genson genson) {
        Assert.notNull(genson, "A Genson instance is required");
        this.genson = genson;
    }

    public Genson getGenson() {
        return this.genson;
    }

    @Override
    protected Object readInternal(Type resolvedType, Reader reader) {
        return getGenson().deserializeInto(reader, resolvedType);
    }

    @Override
    protected void writeInternal(Object object, @Nullable Type type, Writer writer) {
        getGenson().serialize(object, writer);
    }
}

After that you need to register it:

import com.example.genson.GensonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new GensonHttpMessageConverter());
    }
}

See also:

月下客 2025-01-24 02:44:27

对于 Moshi

import com.squareup.moshi.Moshi
import okio.buffer
import okio.sink
import okio.source
import org.springframework.http.MediaType
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter
import java.io.*
import java.lang.reflect.Type

class MoshiHttpMessageConverter(private val jsonParser: Moshi) : AbstractJsonHttpMessageConverter() {

    init {
        this.supportedMediaTypes = listOf(MediaType.APPLICATION_JSON)
    }

    @Throws(Exception::class)
    override fun readInternal(resolvedType: Type, reader: Reader): Any {

        try {
            asInputStream(reader).source().buffer().use { source ->
                val adapter = jsonParser.adapter<Any>(resolvedType)
                return adapter.fromJson(source)!!
            }
        } catch (ex: Throwable) {
            logger.error("Failed to parse json")
            throw ex
        }
    }

    @Throws(Exception::class)
    override fun writeInternal(value: Any, type: Type?, writer: Writer) {

        try {
            val adapter = jsonParser.adapter<Any>(type ?: error("Type is null"))
            asOutputStream(writer).sink().buffer().use { bufferedSink ->
                adapter.toJson(bufferedSink, value)
                bufferedSink.flush()
            }
        } catch (ex: Throwable) {
            logger.error("Failed to create json")
            throw ex
        }
    }

    private fun asInputStream(reader: Reader): InputStream {
        return object : InputStream() {
            @Throws(IOException::class)
            override fun read(): Int {
                return reader.read()
            }
        }
    }

    private fun asOutputStream(writer: Writer): OutputStream {
        return object : OutputStream() {
            @Throws(IOException::class)
            override fun write(b: Int) {
                writer.write(b)
            }
        }
    }
}

For Moshi:

import com.squareup.moshi.Moshi
import okio.buffer
import okio.sink
import okio.source
import org.springframework.http.MediaType
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter
import java.io.*
import java.lang.reflect.Type

class MoshiHttpMessageConverter(private val jsonParser: Moshi) : AbstractJsonHttpMessageConverter() {

    init {
        this.supportedMediaTypes = listOf(MediaType.APPLICATION_JSON)
    }

    @Throws(Exception::class)
    override fun readInternal(resolvedType: Type, reader: Reader): Any {

        try {
            asInputStream(reader).source().buffer().use { source ->
                val adapter = jsonParser.adapter<Any>(resolvedType)
                return adapter.fromJson(source)!!
            }
        } catch (ex: Throwable) {
            logger.error("Failed to parse json")
            throw ex
        }
    }

    @Throws(Exception::class)
    override fun writeInternal(value: Any, type: Type?, writer: Writer) {

        try {
            val adapter = jsonParser.adapter<Any>(type ?: error("Type is null"))
            asOutputStream(writer).sink().buffer().use { bufferedSink ->
                adapter.toJson(bufferedSink, value)
                bufferedSink.flush()
            }
        } catch (ex: Throwable) {
            logger.error("Failed to create json")
            throw ex
        }
    }

    private fun asInputStream(reader: Reader): InputStream {
        return object : InputStream() {
            @Throws(IOException::class)
            override fun read(): Int {
                return reader.read()
            }
        }
    }

    private fun asOutputStream(writer: Writer): OutputStream {
        return object : OutputStream() {
            @Throws(IOException::class)
            override fun write(b: Int) {
                writer.write(b)
            }
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文