三种方式实现Java对象转json下划线格式

定义对象

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order {
    
    private String orderNo;

    private Long productId;

    private String productName;

    private BigDecimal price;

    private Integer quantity;

    private Boolean isPay;
}

测试类

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.math.BigDecimal;

/**
 * @author 向振华
 * @date 2022/03/28 15:42
 */
public class Test {

    public static void main(String[] args) throws JsonProcessingException {

        Order order = new Order();
        order.setProductId(6L);
        order.setProductName("衣服");
        order.setPrice(new BigDecimal("99.8"));
        order.setQuantity(2);
        order.setIsPay(false);

        // 方式一:使用fastjson
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String json1 = JSON.toJSONString(order, config);
        System.out.println(json1);

        // 方式二:使用Gson
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
        Gson gson = gsonBuilder.create();
        String json2 = gson.toJson(order);
        System.out.println(json2);

        // 方式三:使用Jackson
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);
        String json3 = mapper.writeValueAsString(order);
        System.out.println(json3);
    }
}

输出结果略有不同:

{"is_pay":false,"price":99.8,"product_id":6,"product_name":"衣服","quantity":2}
{"product_id":6,"product_name":"衣服","price":99.8,"quantity":2,"is_pay":false}
{"order_no":null,"product_id":6,"product_name":"衣服","price":99.8,"quantity":2,"is_pay":false}

你可能感兴趣的:(常用类库,fastjson,Gson,Jackson,json)