【Java】使用实体组成JSON字符串(字符串中有字母大写和下划线如何处理,以及输出顺序问题)

模拟字段

ID、EMPLOYEE_NO、EMPLOYEE_NAME

目的

将字段拼接成

{"ID":1,"EMPLOYEE_NO":"20231114","EMPLOYEE_NAME":"xiaoming"}

去调用外来接口,不使用参数组成Map的形式,使用实体组成JSON字符串的方式进行操作

实体(Entity)

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * 用户实体
 *
 * @author xiaoming
 * @date 2023/11/14 14:34
 */
public class User {

	@JsonProperty("ID")
    private Long id;

    @JsonProperty("EMPLOYEE_NO")
    private String employeeNo;

    @JsonProperty("EMPLOYEE_NAME")
    private String employeeName;

    @JsonIgnore
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @JsonIgnore
    public String getEmployeeNo() {
        return employeeNo;
    }

    public void setEmployeeNo(String employeeNo) {
        this.employeeNo = employeeNo;
    }

    @JsonIgnore
    public String getEmployeeName() {
        return employeeName;
    }

    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
}

测试(转换成Json字符串)

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 测试
 *
 * @author xiaoming
 * @date 2023/11/14 14:36
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {

    @Test
    public void test() throws JsonProcessingException {
		User user = new User();
        user.setId(1L);
        user.setEmployeeNo("20231114");
        user.setEmployeeName("xiaoming");
		
		String json = new ObjectMapper().writeValueAsString(user);
        System.out.println(json);
	}
}

打印出来

{"ID":1,"EMPLOYEE_NO":"20231114","EMPLOYEE_NAME":"xiaoming"}

参考

@JsonIgnore 与 @JsonProperty 、@JsonSetter 用法
Java 解决实体类转为 JSON 后,顺序不一致问题,JSONObject 转 JSON 后导致顺序不一致问题

你可能感兴趣的:(Java,java,json)