How in Retrofit to process JSON with a field in which different data types come? (Specification: in the answer comes many typed fields, but for example, one free_val is not typed) For example, there is a JSON responce

  • option 1 {free_val: "any text"}
  • option 2 {free_val: {p1: 1, p2: 2}}
  • option 3 {free_val: {[1,2,3]}

How to describe JSON so that a string would always come even if it is an array or structure while {p1: 1, p2: 2} returns as String "{p1: 1, p2: 2}"

class MyModel{ @SerializedName("free_val") @Expose //Может как-то можно указать, что это всегда строка? //чтобы получать {free_val:{p1:1, p2:2}} как "{p1:1, p2:2}" String freeVal; // далее геттеры сеттер } 

    2 answers 2

    You can use the JsonDeserializer directly to the desired field, which will give more flexibility
    Code on kotlin

     class FreeValDeserializer : JsonDeserializer<String> { override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): String { return json.toString() } } 

     class MyModel{ @SerializedName("free_val") @Expose @JsonAdapter(FreeValDeserializer::class) var freeVal: String = "" } 

      For such cases, you need to write your adapter:

       GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(MyModel.class, new JsonDeserializer<MyModel>(){ @Override public MyModel deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { MyModel model = new MyModel(); model.freeVal = json.getAsJsonObject().get("freeVal").toString(); // model.otherFields = json.getAsJsonObject().get("otherFields").getAs... return model; } }); Retrofit client = new Retrofit.Builder() ... .addConverterFactory(GsonConverterFactory.create(builder.create())) .build(); 

      Another option is to declare free_val as a JsonElement and work with it accordingly as with JsonElement ', checking isJsonPrimitive -> string, number ... isJsonObject -> object, etc.

      Threat Written in the editor window, there may be errors in the syntax.