如何将json String反序列化为数组

时间:2018-06-07 12:54:52

标签: android json pojo json-deserialization

我有以下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"
    }
  ]
}

您可以看到所有spec字段都是一个数组,只有一个 - doc-5。 我在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());
}
}

每次我尝试解析这个=错误。但如果我在spec字符串中设置doc-5字段=一切正常!

但是我不知道服务器能给我发送什么答案因为医生可以只有一个专业(在这种情况下spec将是一个字符串)或者他可以有两个或更多(在这种情况下) spec将是一个数组。)

如何在两种情况下创建多用途反序列化器?

2 个答案:

答案 0 :(得分:0)

当你有spec asi单字符串和List / Array从服务器到达时,应用程序是否崩溃或字符串是否包含该List / Array的json?如果确实如此,那么使用Gson或您使用的任何框架解析它应该相对简单。

将此添加为评论,但尚未提供代表,抱歉。​​

答案 1 :(得分:0)

我找到了我的问题的决定。 首先 - 将@Expose注释添加到Doctor POJO类中提交的spec,并为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())
}