2016-09-19 47 views
2

我正在開發一個有很多網絡調用的應用程序,我正在使用它的改造。對於我創建模型類的每個請求,這導致了大量的模型類。所以在那裏任何避免創建不必要的模型類的方法。如何避免在改造中創建模型

+1

你的意思是GSON模型類?是的,有一種方法。不要使用Gson,只能自己解析JSON字符串 –

+0

您可以添加一些示例代碼嗎? –

+0

或始終解析爲散列圖或散列圖陣列 –

回答

0

是的,你可以避免不必要的模型類。

例如:
假設您有5個模型類,Model_class1是主模型類,您必須聲明其他4個子模型類。

class Model_class1 
{ 
    @SerializedName("Model_class2") 
    @Expose 
    private Model_class2 model_class2; 

@SerializedName("Model_class3") 
    @Expose 
    private Model_class3 model_class3; 

@SerializedName("Model_class4") 
    @Expose 
private Model_class4 model_class4; 

@SerializedName("Model_class5") 
    @Expose 
private Model_class5 model_class5; 

} 

如果您想上面的代碼片斷僅Model_class2Model_class3意味着你只需要申報Model_class1和其餘兩個的型號名稱。不需要聲明,也不需要創建這兩個模型類。

0

是的,你可以至少發送請求,但對於接收我從來沒有嘗試過。

使用的JSONObject或JSONArray,並通過他們改造爲@Body

try { 
     JSONObject obj = new JSONObject(); 
     obj.put("username", "username"); 
     obj.put("password", "password"); 
     RetrofitInterface.login(obj); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

這裏是你的更新接口類

public interface RetrofitInterface{ 
    . 
    . 
    @POST(URL) 
    Call login(@Body JSONObject object); 
    . 
    . 
} 
1

對於接受你可以使用JsonElement作爲響應。對於要求您可以在字符串創建JSON並把它作爲我desctibe如下:

接口

@POST("api/") 
    Call<JsonElement> request(@Body RequestBody body); 

請求:

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), inputJsonString); 
    call.enqueue(new Callback<JsonElement>() { 
       @Override 
       public void onResponse(Call<JsonElement> call, Response<JsonElement> response) { 
        if(response.isSuccessful()){ 
         JsonElement jsonElement = response.body(); 
         if(jsonElement.isJsonObject()){ 
         //use any json deserializer to convert to your class. 
        } 
        else{ 
         System.out.println(response.message()); 
        } 
       } 
       @Override 
       public void onFailure(Call<JsonElement> call, Throwable t) { 
        System.out.println("Failed"); 
       } 
      });