2017-06-05 48 views
0

我是Android新手。我需要從JSON列表中獲取字符串列表。它將被添加到Spinner列表中。我有服務器上的列表像如何使用Retrofit 2從JSON列表中獲取列表<String>?

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}]. 

嘗試與改造標量。 響應作爲

[{"bgroup":"A+"},{"bgroup":"A1+"},{"bgroup":"A1-"}] 

但錯誤檢測爲:

預期的字符串,但被BEGIN_OBJECT位於第1個第3列路徑$ [0] *

任何更好的方式來檢索JSON字符串列表?

+0

它清楚地告訴你,它無法從對象來自哪裏讀取字符串。爲什麼不創建一個映射來讓'List '後來直接從'Mapping.bgroup'提取一個字符串呢? –

+0

如果您爲自定義數據對象使用了相同的字符串,則自動翻新會自動爲您提供帶有值的格式化數據對象。所以使用相同的密鑰。並使用依賴編譯'com.squareup.retrofit2:converter-gson:2.0.2' –

+0

@LyubomyrShaydariv感謝您的回答。你可以給這個場景簡單的列表例子嗎? –

回答

0

這是示例代碼:

GroupService groupService = createService(GroupService.class); 

Call<List<Groups>> groupCall = groupService.getGroups(); 

    groupCall.enqueue(new Callback<List<Groups>>() { 
      @Override 
      public void onResponse(retrofit.Response<List<Groups>> response, Retrofit retrofit) { 


      } 

      @Override 
      public void onFailure(Throwable t) { 
       t.printStackTrace(); 

      } 
     }); 

接口:

public interface GroupService { 

@GET("<URL>") 
Call<List<Groups>> getGroups(); 
} 

還可以創建模型的名稱組。

我希望這可以幫助你。

0

進行以下模型類(parcelable)

package com.example; 

import com.google.gson.annotations.Expose; 
import com.google.gson.annotations.SerializedName; 

public class Example implements Parcelable { 

@SerializedName("bgroup") 
@Expose 
private String bgroup; 

public String getBgroup() { 
return bgroup; 
} 

public void setBgroup(String bgroup) { 
this.bgroup = bgroup; 
} 


    protected Example(Parcel in) { 
     bgroup = in.readString(); 
    } 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     dest.writeString(bgroup); 
    } 

    @SuppressWarnings("unused") 
    public static final Parcelable.Creator<Example> CREATOR = new Parcelable.Creator<Example>() { 
     @Override 
     public Example createFromParcel(Parcel in) { 
      return new Example(in); 
     } 

     @Override 
     public Example[] newArray(int size) { 
      return new Example[size]; 
     } 
    }; 
} 

不是創建接口類這樣

public interface ApiService { 

@GET("<URL>") 
Call<List<Example>> getBloodGroups(); 
} 

最後調用改造喜歡以下內容:

Call<List<Example>> call = new RestClient(this).getApiService() 
       .getBloodGroups(); 
     call.enqueue(new Callback<List<Example>>() { 
      @Override 
      public void onResponse(Call<List<Example>> call, Response<List<Example>> response) { 

      } 

      @Override 
      public void onFailure(Call<List<Example>> call, Throwable throwable) { 

      } 
     }); 
+0

是的。你的答案應該有效。但我想使用沒有模型類。任何其他簡單的方式請問? –

+0

所以你想獲得響應作爲JSON字符串?? ?? –

+0

我想添加列表的響應值,然後我可以使用spinner下拉菜單。 最後我創建了簡單的模型類。它的工作現在。謝謝@Krishna Meena –