简体   繁体   中英

How to convert json object from json array to string array in android

My JSON is

[
  {
    "Heading": "Heading 1"
  },
  {
    "Heading": "Heading 2"
  },
  {
    "Heading": "Heading 3"
  }
]

I want this array is converted into

String heading[]={"Heading 1","Heading 2","Heading 3"};

I am using retrofit for load jsonarray. this json link is http://www.mocky.io/v2/5e6f3b37330000a11df077ce

just at the api interface make it returns ArrayList

@GET("http://www.mocky.io/v2/{itemId}")
Call<ArrayList<Item>> getItem(@Path("itemId") String id)

or if you are using RxJava change to

@GET("http://www.mocky.io/v2/{itemId}")
Single<ArrayList<Item>> getItem(@Path("itemId") String id)

Class Item{
  private String Heading;
  //add the getters and setters
}

Use this code to solve your problem.

public void getItemList(String id)
    {
        ApiConfig config = RetrofitClient.getRetrofitInstance().create(ApiConfig.class);
        Call<List<ItemsModel>> call = config.getItmeList(id);

        call.enqueue(new Callback<List<ItemsModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onResponse(@NonNull Call<List<ItemsModel>> call, @NonNull Response<List<ItemsModel>> response) {
                if (response.isSuccessful()) { // response is successful
                    if(response.body() != null)
                    {
                        String[] items = response.body().toArray(new String[0]);//this is string array
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<List<ItemsModel>> call, @NonNull Throwable t) {
                Log.d("errorResponse", Objects.requireNonNull(t.getMessage()));
            }
        });

    }

Item pojo class

public class ItemsModel
{
    @SerializedName("heading")
    private String heading;


    public String getHeading() {
        return heading;
    }

    public void setHeading(String heading) {
        this.heading = heading;
    }
}

Interface

@GET("http://www.mocky.io/v2/{itemId}")
    Call<List<ItemsModel>> getItmeList(@Path("itemId") String id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM