How to create Java receivers and setters when an object key is equal to a number

I cannot create Java Getters and Setters because I got a number (digit) for my object key. I will show you my API response. How can I achieve this without changing the API.

    {"api_status": true,
    "message": "",
     "data": {
        "0": {
          "id": "aaa",
          "name": "aaa",
          "address": "aaa",
          "category": "aaa",
          "open_24_hours": "aaa",
          "business_open": "",
          "business_close": "",
          "type": "0",
          "title": null,
          "latitude": "6.8729428",
          "longitude": "79.8689013",
          "city": "",
          "distance": "2.95555089735992"
           },
       "1": {
          "id": "bbb",
           "name": "bbb",
           "address": "bbb",
           "category": "bbb",
           "open_24_hours": "bbb",
           "business_open": "",
           "business_close": "",
           "type": "0",
           "title": null,
           "latitude": "6.8767581",
           "longitude": "79.8674747",
           "city": "",
           "distance": "2.915385898910569"
         },
   }
  }
+4
source share
7 answers

Use the class below and pass it to the GSON library with your json data and the class as a model. you get your model, each data item is mapped to hashtable, where the key is your number, which I represent as a string. Iterating over the hash map, you will get a keySet, which is your all keys in the json data key. and for each key you can get itemData.

class JsonStructure{
public boolean api_status;
public String message
HashMap<String,ItemsData> data;
}


class ItemsData{
public String id;
public String name;
public String address;
public String category;
public String open_24_hours;
public String business_open;
public String business_close;
public String type;
public String title;
public String latitude;
public String longitude;
public String city;
public String distance;

}

To modify Build

BuildRetrofit(){
 mOkHttpClient = new OkHttpClient.Builder()
                 .addInterceptor(interceptor)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        mConverterFactory = GsonConverterFactory.create();
    String baseUrl = "http://dev.appslanka.com/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(mOkHttpClient)
                .addConverterFactory(mConverterFactory)
                .build();
        mApi = retrofit.create(ApiInterface.class);
        }   

ApiInterface yoyr

interface ApiInterface{

  @GET("_test/placeInDistance/")
Call<JsonStructure> getResponseForApiCall();
}

:

Call<JsonStructure> call = mApi.getResponseForApiCall();
        Response<JsonStructure> response = call.execute();

, :

HashMap<String, ItemsData> map = response .data;
            Set<String> s = map.keySet();
            Iterator<String> i = s.iterator();
            while (i.hasNext()){
                String key = i.next();
                ItemsData data = map.get(key);
                String id = data.id;
                String name = data.name;
                String address = data.address;
                String category = data.category;
                String open24Hr = data.open_24_hours;
                String businessOpen = data.business_open;
                String close = data.business_close;
                String latitue = data.latitude;
                ..... etc

            }
+2

, . SerializedName :

@SerializedName("0")
private MyClass myObject;

MyClass POJO , .

, API ( ), , , , .

+1

JSON. . , . :

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class Response {

public boolean apiStatus;

public String message;

public List<Data> datas;

public Response(JSONObject jsonObject) {
    apiStatus = jsonObject.optBoolean("api_status");
    message = jsonObject.optString("message");
    datas = new ArrayList<>();
    try {
        JSONObject datasJSON = jsonObject.getJSONObject("data");

        int index = 0;
        while (datasJSON.has(String.valueOf(index))) {
            JSONObject dataJSON = datasJSON.getJSONObject(String.valueOf(index));
            datas.add(new Data(dataJSON));
            index++;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override public String toString() {
    return "Response{" +
            "apiStatus=" + apiStatus +
            ", message='" + message + '\'' +
            ", datas=" + datas +
            '}';
}
}

:

import org.json.JSONObject;

public class Data {
public String id;

public String name;

public String address;

public String category;

public String open24Hours;

public String businessOpen;

public String businessClose;

public String type;

public String title;

public String latitude;

public String longitude;

public String city;

public String distance;

public Data(JSONObject jsonObject) {
    id = jsonObject.optString("id");
    name = jsonObject.optString("name");
    address = jsonObject.optString("address");
    category = jsonObject.optString("category");
    open24Hours = jsonObject.optString("open_24_hours");
    businessOpen = jsonObject.optString("business_open");
    businessClose = jsonObject.optString("business_close");
    type = jsonObject.optString("type");
    title = jsonObject.optString("title");
    latitude = jsonObject.optString("latitude");
    longitude = jsonObject.optString("longitude");
    city = jsonObject.optString("city");
    distance = jsonObject.optString("distance");
}

@Override public String toString() {
    return "Data{" +
            "id='" + id + '\'' +
            ", name='" + name + '\'' +
            ", address='" + address + '\'' +
            ", category='" + category + '\'' +
            ", open24Hours='" + open24Hours + '\'' +
            ", businessOpen='" + businessOpen + '\'' +
            ", businessClose='" + businessClose + '\'' +
            ", type='" + type + '\'' +
            ", title='" + title + '\'' +
            ", latitude='" + latitude + '\'' +
            ", longitude='" + longitude + '\'' +
            ", city='" + city + '\'' +
            ", distance='" + distance + '\'' +
            '}';
}
}

:

Response response = new Response(jsonObject);

Retrofit2. factory, ResponseRetrofitConverter :

import android.support.annotation.NonNull;

import org.json.JSONObject;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class ResponseRetrofitConverter extends Converter.Factory {

public static ResponseRetrofitConverter create() {
    return new ResponseRetrofitConverter();
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    return new JsonConverter();
}

private final static class JsonConverter implements Converter<ResponseBody, Response> {

    @Override
    public Response convert(@NonNull ResponseBody responseBody) {
        try {
            return new Response(new JSONObject(responseBody.string()));
        } catch (Exception e) {
            return null;
        }
    }
}
}

Response , factory, :

.addConverterFactory(ResponseRetrofitConverter.create())

, :

Retrofit.Builder()
            .baseUrl(link)
            .addConverterFactory(ResponseRetrofitConverter.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();
+1

java List .

0

Json, , json- Jackson, :

@JsonProperty("0")
private CustomObject zero;
@JsonProperty("1")
private CustomObject one;
public CustomObject getZero()
{
    return this.zero;
}
public void setZero(CustomObject zero)
{
    this.zero= zero;
}

public CustomObject getOne()
{
    return this.one;
}
public void setOne(CustomObject one)
{
    this.one= one;
}
0

_0, _1... .

0

If you are using Gson, you can use the following:

public class Model{

@SerializedName("0")
private String object;

}
0
source

Source: https://habr.com/ru/post/1681846/


All Articles