关于Java的enum枚举属性与Json字符串之间的互转

可能很多人遇到过类似的问题:Java的enum枚举属性与Json字符串之间的互转,但json字符串结果是enum枚举的名称,不是想要的翻译的结果----按枚举类的某个属性值翻译。那么最简单方法是在enum枚举类中实现属性字段定义,在get方法上添加注解@JsonValue。如下面的示例:

import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.Serializable;
import java.text.SimpleDateFormat;

public class TestEnum {

    public enum StatusEnum {
        NODE(0, "无"),
        START(1, "开始"),
        END(2, "结束");

        private Integer code;
        private String name;

        private StatusEnum(Integer code, String name) {
            this.code = code;
            this.name = name;
        }

        @JsonValue
        public Integer getCode() {
            return code;
        }

        public void setCode(Integer code) {
            this.code = code;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static class Person implements Serializable {
        private String name;
        private String id;
        private StatusEnum status;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getId() {
            return id;
        }

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


        public StatusEnum getStatus() {
            return status;
        }

        public void setStatus(StatusEnum status) {
            this.status = status;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", id='" + id + '\'' +
                    ", status=" + status +
                    '}';
        }
    }

    public static void main(String[] args) {
        TestEnum.Person person = new TestEnum.Person();
        person.setId("1111");
        person.setName("Jack.Ma");
        person.setStatus(StatusEnum.START);

        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
            String value = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
            System.out.println(value);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            TestEnum.Person person1=mapper.readValue(value, TestEnum.Person.class);
            System.out.println(person1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出结果:

Person对象翻译成Json字符串
{
“name” : “Jack.Ma”,
“id” : “1111”,
“status” : 1
}

Json字符串翻译成Person对象:
Person{name=‘Jack.Ma’, id=‘1111’, status=START}

以上内容希望能帮助大家解决问题。

你可能感兴趣的:(问题解决,java)