Вот простой BaseEnum
интерфейс,
public interface BaseEnum {
Object getCode();
String getText();
}
Вот EnmLanguage
, реализующий BaseEnum
интерфейс,
public enum EnmLanguage implements BaseEnum {
en_US("en_US", "English"),
en_UK("en_UK", "English"),
tr_TR("tr_TR", "Turkish");
private String code;
private String text;
EnmLanguage(String code, String text) {
this.code = code;
this.text = text;
}
@Override
public String getCode() {
return code;
}
@Override
public String getText() {
return text;
}
}
Вот еще EnmElement
, реализующий BaseEnum
interface,
public enum EnmElement implements BaseEnum {
H("H", "Hydrogen"),
He("He", "Helium"),
Li("Li", "Lithium");
private String code;
private String text;
EnmElement(String code, String text) {
this.code = code;
this.text = text;
}
@Override
public String getCode() {
return code;
}
@Override
public String getText() {
return text;
}
}
Вот простой модульный тест,
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class EnumTest {
@Test
public void testDeserializeLanguage() throws IOException {
ObjectMapper mapper = new ObjectMapper();
EnmLanguage[] expected = {EnmLanguage.en_US, EnmLanguage.tr_TR};
EnmLanguage[] actual = mapper
.readerFor(EnmLanguage[].class)
.readValue(mapper.writeValueAsString(expected));
assertNotNull(actual);
assertArrayEquals(expected, actual);
}
@Test
public void testDeserializeElement() throws IOException {
ObjectMapper mapper = new ObjectMapper();
EnmElement[] expected = {EnmElement.H, EnmElement.He, EnmElement.Li};
EnmElement[] actual = mapper
.readerFor(EnmElement[].class)
.readValue(mapper.writeValueAsString(expected));
assertNotNull(actual);
assertArrayEquals(expected, actual);
}
}
Немного более сложный пример с использованием перечислений,
import lombok.Data;
@Data
public class CompositeExample {
private String name;
private EnmLanguage[] lands;
private EnmElement[] elements;
}
Пример фрагмента модульного теста,
@Test
public void testDeserialize() throws IOException {
CompositeExample expected = new CompositeExample();
String name = "Hello";
expected.setName(name);
EnmLanguage[] langs = {EnmLanguage.en_US, EnmLanguage.tr_TR};
expected.setLangs(langs);
EnmElement[] elements = {EnmElement.H, EnmElement.He, EnmElement.Li};
expected.setElements(elements);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(expected);
//{"name":"Hello","langs":["en_US","tr_TR"],"elements":["H","He","Li"]}
CompositeExample actual = mapper
.readerFor(CompositeExample.class)
.readValue(json);
assertNotNull(actual);
assertEquals(expected, actual);
}