我将RetrofitPOJO一起使用,通常可以使用,但是根据结果是否有效,答案有两个不同的对象。哪个是String,另一个是Object

{
  "data":"No results."
}


要么:

{
  "data": {
    "exame": [
      {
        "id": 776,
        "codigo": "DHT",
        "instrucao": "- Text."
      },
      {
        "id": 776,
        "codigo": "DHT",
        "instrucao": "- Text"
      }
    ]
  }
}


而我的班级:

public class Exame {

    @SerializedName("data")
    @Expose
    @Nullable
    private ExameItem exameItem;
    private String mensagem;

    public ExameItem getExameItem() {
        return exameItem;
    }

    public void setExameItem(ExameItem exameItem) {
        this.exameItem = exameItem;
    }

    public String getMensagem() {
        return mensagem;
    }

    public void setMensagem(String mensagem) {
        this.mensagem = mensagem;
    }
}


当我做Exame().getExameItem很好时,但是当我尝试测试Exame().getMessagem中是否有消息时,会给我带来这个错误:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 10 path $.data


因此,我认为如何测试@data是否为StringObject,但是我不知道如何做,任何人都可以帮忙吗?

最佳答案

您需要通过实现JsonDeserializer接口来实现自定义解串器。请参见以下示例:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.annotations.JsonAdapter;

import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.List;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().create();

        System.out.println(gson.fromJson(new FileReader(jsonFile), Exame.class));
    }
}

class ExamsJsonDeserializer implements JsonDeserializer<Exame> {

    @Override
    public Exame deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject root = json.getAsJsonObject();
        JsonElement data = root.get("data");

        Exame exam = new Exame();
        if (data.isJsonPrimitive()) {
            exam.setMensagem(data.getAsString());
        } else {
            ExameItem examItem = context.deserialize(data, ExameItem.class);
            exam.setExameItem(examItem);
        }
        return exam;
    }
}

@JsonAdapter(ExamsJsonDeserializer.class)
class Exame {

    private ExameItem exameItem;
    private String mensagem;

    // getters, setters, toString
}

class ExameItem {

    private List<Item> exame;

    //getters, setters, toString
}

class Item {

    private int id;
    // ...
    //getters, setters, toString
}

07-23 19:01