我已经关注了JSON。
{
"code": 200,
"status": "success",
"request": [],
"total": 10,
"count": 10,
"offset": 0,
"limit": 100,
"response": [
{
"uid": "doc-1",
"name": "Иванов Иван Иванович",
"spec": [
"Врач лабораторной диагностики",
"Врач-терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/01.jpg"
},
{
"uid": "doc-10",
"name": "Попов Евгений Олегович",
"spec": [
"Врач ренгенолог"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/10.jpg"
},
{
"uid": "doc-2",
"name": "Петров Сергей Иванович",
"spec": [
"Врач лабораторной диагностики",
"Врач диетолог",
"врач-терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/02.jpg"
},
{
"uid": "doc-3",
"name": "Сидоров Сергей Константинович",
"spec": [
"Врач лабораторной диагностики",
"Врач - ренгенолог"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/03.jpg"
},
{
"uid": "doc-4",
"name": "Константинов Александр Константинович",
"spec": [
"Врач лабораторной диагностики",
"Врач-терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/04.jpg"
},
{
"uid": "doc-5",
"name": "Сергеев Иван Константинович",
"spec": "Врач лабораторной диагностики",
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/05.jpg"
},
{
"uid": "doc-6",
"name": "Попов Дмитрий Данилович",
"spec": [
"Врач лабораторной диагностики",
"Врач ренгенолог"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/06.jpg"
},
{
"uid": "doc-7",
"name": "Иванова Екатерина Павловна",
"spec": [
"Врач терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/07.jpg"
},
{
"uid": "doc-8",
"name": "Екатеринина Лада Павловна",
"spec": [
"Врач терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/08.jpg"
},
{
"uid": "doc-9",
"name": "Васильева Екатерина Олеговна",
"spec": [
"Врач терапевт"
],
"photo": "http://demo-api.atlas-patiente.office.prosvdigital.ru/img/doctor/09.jpg"
}
]
}正如您所看到的,除了one - doc-5之外,所有的spec字段都是一个数组。我在Retrofit中获得了数据。这是我对此响应的POJO。
public class Doctor implements IDObject<String>, Serializable {
public static final String FIELD_NAME = "name";
@SerializedName("uid")
private String id;
@SerializedName("name")
private String name;
@SerializedName("doctorShortName")
private String shortName;
@SerializedName("spec")
private List<String> speciality;
@SerializedName("photo")
private String photoUrl;
public String getName() {
return name;
}
public String getPhotoUrl() {
return photoUrl;
}
public List<String> getSpeciality() {
return speciality;
}
public String getShortName() {
return shortName;
}
@Override
public String getId() {
return id;
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Doctor && ((Doctor) obj).getId().equals(getId());
}
}每次我尝试解析this = error时。但是如果我让doc-5中的String字段= spec,一切都好!
但我不知道服务器可以发送给我什么答案,因为医生可以只有一个专业(在本例中,spec将是一个字符串),也可以有两个或更多(在本例中,spec将是一个数组)。
如何创建在这两种情况下都能工作的多用途反序列化程序?
发布于 2018-06-07 21:22:45
当你有来自服务器的spec ASI单字符串和列表/数组到达时,应用程序是否崩溃,或者字符串是否包含该列表/数组的json?如果是这样,那么使用Gson或您正在使用的任何框架解析它应该是相对简单的。
我会将此添加为评论,但还没有足够的代表,抱歉。
发布于 2018-06-07 23:01:51
我发现了我的问题的一个决定。首先,向Doctor POJO类中的spec文件添加@Expose注释,并为spec添加setter。
public class Doctor implements IDObject<String>, Serializable {
public static final String FIELD_NAME = "name";
@SerializedName("uid")
private String id;
@SerializedName("name")
private String name;
@SerializedName("doctorShortName")
private String shortName;
@Expose(deserialize = false)
private List<String> speciality;
@SerializedName("photo")
private String photoUrl;
public String getName() {
return name;
}
public String getPhotoUrl() {
return photoUrl;
}
public List<String> getSpeciality() {
return speciality;
}
public String getShortName() {
return shortName;
}
@Override
public String getId() {
return id;
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public boolean equals(Object obj) {
return obj instanceof Doctor && ((Doctor) obj).getId().equals(getId());
}
public void setSpeciality(List<String> speciality) {
this.speciality = speciality;
}
}添加这是反序列化程序
public class FooDeserializer implements JsonDeserializer<Doctor> {
@Override
public Doctor deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
Type type = new TypeToken<DoctorChild>() {}.getType();
Doctor foo = context.deserialize(json, type);
JsonElement specField = json.getAsJsonObject().get("spec");
if (specField != null && !specField.isJsonNull()) {
List<String> specs = new ArrayList<>();
if (specField.isJsonArray()) {
JsonArray specList = specField.getAsJsonArray();
Iterator<JsonElement> iterator = specList.iterator();
while (iterator.hasNext()) {
JsonElement element = iterator.next();
String spec = element != null && !element.isJsonNull() ? element.getAsString() : null;
specs.add(spec);
}
} else if (specField.isJsonPrimitive()) {
JsonPrimitive specPrimitive = specField.getAsJsonPrimitive();
if (specPrimitive.isString()) {
String spec = specPrimitive.getAsString();
specs.add(spec);
}
}
foo.setSpeciality(specs);
}
return foo;
}
}然后将其添加到GsonConfiguration中
private static GsonBuilder base() {
return new GsonBuilder()
.addSerializationExclusionStrategy(new SerializeExclusionStrategy())
.addDeserializationExclusionStrategy(new DeserializeExclusionStrategy())
.registerTypeAdapter(Doctor.class, new FooDeserializer())
}https://stackoverflow.com/questions/50741771
复制相似问题