Java中的JSON处理:Jackson与Gson

大家好,我是微赚淘客系统3.0的小编,是个冬天不穿秋裤,天冷也要风度的程序猿!今天我们来讨论Java中处理JSON的两大流行库:Jackson和Gson。

一、什么是JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。Java开发中常用的两个JSON处理库是Jackson和Gson。

二、Jackson简介

Jackson是一个功能强大且高性能的JSON处理库,广泛应用于Java开发中。它提供了数据绑定、树模型和流API三种处理JSON的方式。

1. 添加Jackson依赖

在Maven项目中添加Jackson的依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

2. Jackson示例代码

下面是使用Jackson进行JSON序列化和反序列化的示例:

package cn.juwatech.json;

import com.fasterxml.jackson.databind.ObjectMapper;

class User {
    public String name;
    public int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class JacksonExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();

        // 序列化:Java对象到JSON
        User user = new User("Alice", 30);
        String jsonString = mapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + jsonString);

        // 反序列化:JSON到Java对象
        String jsonInput = "{\"name\":\"Bob\",\"age\":25}";
        User deserializedUser = mapper.readValue(jsonInput, User.class);
        System.out.println("Deserialized User: " + deserializedUser.name + ", " + deserializedUser.age);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

三、Gson简介

Gson是Google提供的一个开源Java库,用于将Java对象转换为JSON表示形式,也可以将JSON字符串转换回Java对象。Gson简洁且易于使用。

1. 添加Gson依赖

在Maven项目中添加Gson的依赖:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

2. Gson示例代码

下面是使用Gson进行JSON序列化和反序列化的示例:

package cn.juwatech.json;

import com.google.gson.Gson;

class User {
    public String name;
    public int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class GsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();

        // 序列化:Java对象到JSON
        User user = new User("Alice", 30);
        String jsonString = gson.toJson(user);
        System.out.println("Serialized JSON: " + jsonString);

        // 反序列化:JSON到Java对象
        String jsonInput = "{\"name\":\"Bob\",\"age\":25}";
        User deserializedUser = gson.fromJson(jsonInput, User.class);
        System.out.println("Deserialized User: " + deserializedUser.name + ", " + deserializedUser.age);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.

四、Jackson与Gson的比较

两者各有优缺点,根据具体需求选择适合的库。

1. Jackson的优点

  • 性能优越:Jackson通常比Gson更快,适用于大数据量的处理。
  • 功能丰富:Jackson支持更多高级特性,如注解、自定义序列化和反序列化、树模型、流API等。
  • 社区支持:Jackson有广泛的社区支持和丰富的第三方集成。

2. Gson的优点

  • 易于使用:Gson API设计简洁,易于上手。
  • 灵活性强:Gson在处理嵌套结构和泛型时非常灵活。
  • 小巧轻便:Gson的库体积较小,适合对资源要求较高的应用场景。

五、实际应用场景

1. Spring Boot项目中的应用

Spring Boot项目通常使用Jackson作为默认的JSON处理库,但也可以轻松切换到Gson。以下是在Spring Boot中配置Gson的示例:

package cn.juwatech.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.GsonHttpMessageConverter;

@Configuration
public class GsonConfig {
    @Bean
    public GsonHttpMessageConverter gsonHttpMessageConverter() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(gson);
        return converter;
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

2. 自定义序列化与反序列化

在实际开发中,可能需要自定义序列化和反序列化逻辑。以下是Jackson和Gson的示例:

Jackson自定义序列化与反序列化:

package cn.juwatech.json;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;

class CustomUser {
    public String name;
    @JsonSerialize(using = AgeSerializer.class)
    @JsonDeserialize(using = AgeDeserializer.class)
    public int age;

    public CustomUser() {
    }

    public CustomUser(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

class AgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(value + " years");
    }
}

class AgeDeserializer extends JsonDeserializer<Integer> {
    @Override
    public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String text = p.getText();
        return Integer.parseInt(text.split(" ")[0]);
    }
}

public class JacksonCustomExample {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        CustomUser user = new CustomUser("Alice", 30);

        String jsonString = mapper.writeValueAsString(user);
        System.out.println("Serialized JSON: " + jsonString);

        String jsonInput = "{\"name\":\"Bob\",\"age\":\"25 years\"}";
        CustomUser deserializedUser = mapper.readValue(jsonInput, CustomUser.class);
        System.out.println("Deserialized User: " + deserializedUser.name + ", " + deserializedUser.age);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.

Gson自定义序列化与反序列化:

package cn.juwatech.json;

import com.google.gson.*;

import java.lang.reflect.Type;

class CustomUser {
    public String name;
    public int age;

    public CustomUser() {
    }

    public CustomUser(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

class AgeSerializer implements JsonSerializer<Integer> {
    @Override
    public JsonElement serialize(Integer src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(src + " years");
    }
}

class AgeDeserializer implements JsonDeserializer<Integer> {
    @Override
    public Integer deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String text = json.getAsString();
        return Integer.parseInt(text.split(" ")[0]);
    }
}

public class GsonCustomExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Integer.class, new AgeSerializer())
                .registerTypeAdapter(Integer.class, new AgeDeserializer())
                .create();
        CustomUser user = new CustomUser("Alice", 30);

        String jsonString = gson.toJson(user);
        System.out.println("Serialized JSON: " + jsonString);

        String jsonInput = "{\"name\":\"Bob\",\"age\":\"25 years\"}";
        CustomUser deserializedUser = gson.fromJson(jsonInput, CustomUser.class);
        System.out.println("Deserialized User: " + deserializedUser.name + ", " + deserializedUser.age);
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.

总结

本文介绍了Java中两大流行的JSON处理库:Jackson和Gson。我们详细讲解了如何使用这两个库进行JSON序列化和反序列化,并展示了它们的实际应用场景,包括在Spring Boot项目中的使用和自定义序列化与反序列化。选择使用哪个库可以根据具体需求进行权衡,两者各有优劣,适用于不同的应用场景。

本文著作权归聚娃科技微赚淘客系统开发者团队,转载请注明出处!