要将Java对象转换为JSON,请使用enum
类型的注释。假设我们有这种类型:
public enum MyEnum {
HELLO,
WORLD
}
然后我们以这种方式使用它:
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import java.io.Serializable;
import java.util.List;
public class SerializableObject implements Serializable{
@Enumerated(EnumType.STRING)
private MyEnum singleValue;
// What annotation do I put here?
private List<MyEnum> multiValue;
}
我的问题是:列表multiValue
上的注释是什么,以便包含的枚举值被正确序列化?
答案 0 :(得分:2)
您可以使用EnumType.ORDINAL
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
enum MyEnum {
HELLO, WORLD
}
public class SerializableObject implements Serializable {
@Enumerated(EnumType.STRING)
private MyEnum singleValue;
// What annotation do I put here?
@Enumerated(EnumType.ORDINAL)
private List<MyEnum> multiValue;
public void show() {
multiValue = new ArrayList<>(Arrays.asList(MyEnum.values()));
multiValue.stream().forEach(
element -> System.out.println(element.ordinal() + " " + element.toString()));
}
public static void main(String[] args) {
new SerializableObject().show();
}
}
答案 1 :(得分:0)
以下是进行序列化和反序列化的完整代码。希望 这有助于探索更多。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.fasterxml.jackson.core.JsonProcessingException;
enum MyEnum {
HELLO, WORLD
}
public class SerializableObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Enumerated(EnumType.ORDINAL)
private MyEnum singleValue;
// What annotation do I put here?
@Enumerated(EnumType.STRING)
private List<MyEnum> multiValue;
public void show() {
multiValue = new ArrayList<>(Arrays.asList(MyEnum.values()));
singleValue=MyEnum.HELLO;
}
public static void main(String[] args) throws JsonProcessingException {
SerializableObject a = new SerializableObject();
a.show();
try {
FileOutputStream fileOut = new FileOutputStream("E:\\path\\Crunchify_Test1.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(a);
out.close();
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
FileInputStream fileIn = new FileInputStream("E:\\path\\Crunchify_Test1.txt");
ObjectInputStream in = new ObjectInputStream(fileIn);
// List<MyEnum> multiValue=(List<MyEnum>) in.readObject();
System.out.println("Deserialized Data: \n" + in.readObject().toString());
in.close();
fileIn.close();
} catch (Exception e) {
}
}
@Override
public String toString() {
return "SerializableObject [singleValue=" + singleValue + ", multiValue=" + multiValue
+ "]";
}
}