Simple case sensitivity

I am trying to create XML using simplexml library (v2.6.2) http://simple.sourceforge.net/home.php

The XML I want to create must contain an enumeration value that must be case sensitive. Following is the POJO:

 package pojos;

public enum MyEnum {

    NEW("new"),
    OLD("old");

     private final String value;

     MyEnum(String v)
     {
         value = v;
     }

     public String value() {
            return value;
        }

        public static MyEnum fromValue(String v) {
            for (MyEnum c: MyEnum.values()) {
                if (c.value.equals(v)) {
                    return c;
                }
            }
            throw new IllegalArgumentException(v);
        }

}

Below is the serialization code:

import java.io.File;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import pojos.MyEnum;


public class TestEnum {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        Serializer serializer = new Persister();
        MyEnum example = MyEnum.NEW;
        File result = new File("myenum.xml");

        serializer.write(example, result);

    }

}

Result:

<myEnum>NEW</myEnum>

Desired Result:

<myEnum>NEW</myEnum>

How do I proceed? I can’t change the name of the variable in the listing, because this is the keyword β€œnew”!

Thank.

+2
source share
3 answers

, Transform . EnumTransform. , Transform. Transform toString() name() .

class MyEnumTransform implements Transform<Enum> {
    private final Class type;

    public MyEnumTransform(Class type) {
        this.type = type;
    }

    public Enum read(String value) throws Exception {
        for (Object o : type.getEnumConstants()) {
            if (o.toString().equals(value)) {
                return (Enum) o;
            }
        }
        return null;
    }

    public String write(Enum value) throws Exception {
        return value.toString();
    }
}

Transform match Matcher. Matcher. , , Transformer. Matcher Persister. .

Persister serializer = new Persister(new Matcher() {
    public Transform match(Class type) throws Exception {
        if (type.isEnum()) {
            return new MyEnumTransform(type);
        }
        return null;
    }
 });

, toString enum. , toString.

+11

, , - ... ( ) .

0

You have to override toString()

@Override 
public String toString() {
       return this.value.toLowerCase();
}

Then record the results using

serializer.write(example.toString(), result);
0
source

Source: https://habr.com/ru/post/1792247/


All Articles