簡體   English   中英

使用Retrofit2解析JSON

[英]Parse JSON using retrofit2

我是Android開發的新手,這是我的問題:服務器有這樣的json響應:

{
"China": [
    "Guangzhou",
    "Fuzhou",
    "Beijing",
    ... (other cities)],
"Japan": [
    "Tokyo",
    "Hiroshima",
    ... (other cities)],
...(other countries)
}

等等。 如何使用Retrofit2保存國家名稱和城市清單? 我嘗試了這個:

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";
private static final String BASE_URL = "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    CountriesAPI countriesAPI = retrofit.create(CountriesAPI.class);
    Call<Country> call = countriesAPI.getCountries();

    call.enqueue(new Callback<Country>() {
        @Override
        public void onResponse(Call<Country> call, Response<Country> response) {
            Log.d(TAG, "onResponse: Server Response: " + response.toString());
            Log.d(TAG, "onResponse: received information: " + response.body().toString());

            ArrayList<String> citiesList = response.body().getCities();
            for(int i = 0; i<citiesList.size(); i++){
                Log.d(TAG, "onResponse: \n" +
                "country: " + citiesList.get(i)
                );
            }
        }

        @Override
        public void onFailure(Call<Country> call, Throwable t) {
            Log.e(TAG, "onFailure: Something went wrong" + t.getMessage());
            Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    });
}
}

public interface CountriesAPI {

String BASE_URL = "https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities";

@GET(".json")
Call<Country> getCountries();
}

public class Country {

@SerializedName("country")
@Expose
private ArrayList<String> countrys;

@SerializedName("country")
@Expose
private ArrayList<String> cities;

public ArrayList<String> getCountrys() {
    return countrys;
}

public void setCountrys(ArrayList<String> countrys) {
    this.countrys = countrys;
}

public ArrayList<String> getCities() {
    return cities;
}

public void setCities(ArrayList<String> cities) {
    this.cities = cities;
}

@Override
public String toString() {
    return "Country{" +
            "countrys=" + countrys +
            ", cities=" + cities +
            '}';
}
}
 @SerializedName("China")
 @Expose
 private ArrayList<String> countrys;

 @SerializedName("Japan")
 @Expose
 private ArrayList<String> cities;

 Change your SerializedName.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM