如何在对象键为数字时创建 Java getter 和 setter



我无法创建Java Getters和seters,因为我得到了对象键的数字(数字(。 我将向您展示我的 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"
},
}
}

使用以下类并将其与 json 数据和类作为模型一起传递给 GSON 库。 您将获得模型,每个数据项都与哈希表映射,其中键是您的数字,我将其表示为字符串 通过迭代哈希映射,您将获得keySet,这是json数据键中的所有键。 对于每个键,您可以获取 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;
}

用于改造 构建

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);
}   

在 API 接口中定义 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
}

是的,你可以。使用如下所示SerializedName注释:

@SerializedName("0")
private MyClass myObject;

MyClass将代表您要返回的数据的POJO

我只想指出,更好的解决方案是更改API(因为此响应很奇怪(,返回一个列表而不是带有键数字的对象,但我可以看到您在问题中写道你不能改变它。

如果你真的需要解析这个 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时使用它的说明。 首先,我们需要创建自定义工厂,创建名为 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;
}
}
}
}

当响应是您的实体时, 添加与工厂的连接以使用以下代码行进行改造:

.addConverterFactory(ResponseRetrofitConverter.create())

例如我的代码:

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

您应该创建一个对象的 javaList来表示数据。

如果要绑定以数字作为名称的 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;
}

如果您使用的是 Gson,那么您可以按如下方式使用:

public class Model{
@SerializedName("0")
private String object;
}

你可以称你为类_0_1...甚至有点奇怪。

最新更新