[英]how to create Java getters and setters when object key is number
I cannot create Java Getters and Setters, because I got number(digit) for my Object Key. 我无法创建Java Getters和Setter,因为我得到了Object Key的数字(数字)。 I will show you my API response.
我将向您展示我的API响应。 How can I achieve this without changing the API.
如何在不更改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"
},
}
}
Use the below class and pass it to GSON library with your json data and the Class As a model . 使用下面的类并使用您的json数据和类作为模型将其传递给GSON库。 you will get your model, each data item is mapped with hashtable where key is your number which i represent as string By iterating over hash map you will get keySet which is your all keys in the data key of json.
你将得到你的模型,每个数据项都用哈希表映射,其中key是你的数字,我表示为字符串通过迭代哈希映射,你将获得keySet,这是你在json的数据键中的所有键。 and for each key you can get itemData.
并且对于每个键,您可以获得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;
}
For retrofit Build 对于改造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);
}
In ApiInterface define yoyr request method 在ApiInterface中定义yoyr请求方法
interface ApiInterface{
@GET("_test/placeInDistance/")
Call<JsonStructure> getResponseForApiCall();
}
Now call this method as retrofit call structure: 现在将此方法称为改进调用结构:
Call<JsonStructure> call = mApi.getResponseForApiCall();
Response<JsonStructure> response = call.execute();
Parse this response like below: 解析此响应如下:
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
}
Yes, you can. 是的你可以。 Use
SerializedName
annotation like this: 像这样使用
SerializedName
注释:
@SerializedName("0")
private MyClass myObject;
Where MyClass
is gonna represent a POJO
for the data you're getting back. MyClass
将代表您正在获取的数据的POJO
。
I just want to note that a better solution would be to change the API (cause this response is weird), to return a list rather than an object with digits for keys, but I can see that you wrote in the question that you cannot change it.
我只想注意一个更好的解决方案是更改API (因为这个响应很奇怪),返回一个列表而不是一个带有数字键的对象,但我可以看到你在问题中写道你不能改变它。
If you really need to parse this JSON. 如果你真的需要解析这个JSON。 Use custom solution.
使用定制解决方案 For example my solution.
例如我的解决方案。 Create class Response with following code :
使用以下代码创建类Response:
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 +
'}';
}
}
Create class Data with following code : 使用以下代码创建类数据:
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 + '\'' +
'}';
}
}
Instruction for use this solution: 使用此解决方案的说明:
Response response = new Response(jsonObject);
Instruction for use it, when you use Retrofit2. 使用Retrofit2时的使用说明。 For first we need to create custom factory, create class with name ResponseRetrofitConverter, and this following code :
首先,我们需要创建自定义工厂,创建名为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;
}
}
}
}
When Response is your entity, Add connect with factory to retrofit use following code line : 当Response是您的实体时,使用以下代码行添加连接工厂以改进使用:
.addConverterFactory(ResponseRetrofitConverter.create())
For example my code: 例如我的代码:
Retrofit.Builder()
.baseUrl(link)
.addConverterFactory(ResponseRetrofitConverter.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
您应该创建一个java对象List
来表示数据。
If you want to bind a Json that has a number as name, and if you are using jackson as json library, you can declare the variable as follow: 如果要绑定一个具有数字作为名称的Json,并且如果您使用jackson作为json库,则可以将变量声明如下:
@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
, _1
......即使它有点奇怪。
If you are using Gson then you can use as follows: 如果您正在使用Gson,那么您可以使用如下:
public class Model{
@SerializedName("0")
private String object;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.