我需要制作以下json:
[ { "contentType": "folder" },
{ "contentType": "image" },
{ "contentType": "video" }
]
解析成这样的数组:
FileStructureElement [] elements[];
具有:
public class FileStructureElement {
private ElementType contentType;
}
public enum ElementType {
FOLDER, IMAGE, VIDEO, DEFAULT;
}
这是一个简化的示例,FileStructureElement
类具有更多的属性,与问题字段无关。
我想将contentType
property的值加载为的值ElementType
。我负担不起使枚举的值与json的类型匹配,因为json中的可能值之一是“ default”,这不是有效的枚举值。此外,我不希望使用小写名称的枚举值。这基本上意味着我需要自定义GSON解析。有人可以帮我吗?
这里的想法(检查我解析的属性的值并选择是否加载枚举值)对我没有帮助,因为我无法控制要与之交谈的Web服务接口,并且这些值太明显了,我冒着风险,它们也将作为其他json属性的值出现。
如果要对枚举进行自定义解析,则需要注册适配器
JsonDeserializer<?> jd = new JsonDeserializer<ElementType>() {
@Override
public ElementType deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
String enumStr = json.getAsString();
ElementType val =
//...
return val;
}
};
Gson gson = new GsonBuilder().registerTypeAdapter(ElementType.class, jd).create();
只需为提供的String返回正确的枚举值即可。
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다