Home  >  Article  >  Is there a way to (de)serialize Java enums with YAML?

Is there a way to (de)serialize Java enums with YAML?

WBOY
WBOYforward
2024-02-08 22:15:18895browse

php editor Strawberry answered: Yes, there is a way to serialize and deserialize Java enumerations and YAML. Java enumerations can be serialized and deserialized using Jackson, Gson, or other JSON libraries. YAML is a human-friendly data format that can also be used to serialize and deserialize Java enums via Jackson, SnakeYAML, or other YAML libraries. Using these libraries, you can easily convert Java enumerations to YAML for data transmission and storage.

Question content

I'm trying to serialize and deserialize a Java object containing an enum to/from a YAML representation. I'm trying to use the Jackson (com.fasterxml.jackson) package to do this.

I keep getting this exception:

Caused by: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.beastcode.devops.prometheusbroker.domain.Metric$Type` from String "counter": not one of the values accepted for Enum class: [GAUGE, COUNTER]

I'm assuming I need some kind of adapter or converter, but don't know what's available for YAML (if any).

for reference:

Metric.java:

public class Metric {

  public enum Type {
    COUNTER, GAUGE
  }

  private String           name;
  private String           description;
  private Type             type;
  private List<String>     labels;
  private List<MetricData> data;

  // getters/setters removed
}

data.yaml:

---
name: gitlab_pipeline_success_total
description: "blah blah blah"
type: counter
labels:
  - project
  - somethingElse
data:

Parser.java:

public class Parser {

  private ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

  public void parse() throws StreamReadException, DatabindException, IOException {
    Metric m = mapper.readValue(new File("data.yaml"), Metric.class);
  }

}

Solution

By default, Jackson uses the valueOf method of the enumeration. case sensitive.

You can easily change this by adding a static method annotated with @JsonCreator:

public class Metric {

    public enum Type {
        COUNTER, GAUGE;

        @JsonCreator
        public static Type getType(String value) {
            return valueOf(value.toUpperCase());
        }

        // optional, for serialization
        @JsonValue
        public String value() {
            return name().toLowerCase();
        }
    }

    // rest omitted
}

The above is the detailed content of Is there a way to (de)serialize Java enums with YAML?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete