Android 如何在JSONarray中使用动态键编写Pojo

Android 如何在JSONarray中使用动态键编写Pojo,android,retrofit,pojo,Android,Retrofit,Pojo,我甚至不知道这是否是一个有效的问题,但我很难将API结果转换为POJO,因为有些键是动态的 { "data": [{ "something_edit": true }, { "test_null": false } ], "success": true } 正如您所看到的,密钥内部的数据是动态的。我尝试使用jsonschema2pojo或其他转换器,但它声明了一个命名变量,这不是一个好结果。顺便说一句,我使用的是改装和GSON库 编辑:

我甚至不知道这是否是一个有效的问题,但我很难将API结果转换为POJO,因为有些键是动态的

{
"data": [{
        "something_edit": true
    },
    {
        "test_null": false
    }
],
"success": true
}

正如您所看到的,密钥内部的数据是动态的。我尝试使用jsonschema2pojo或其他转换器,但它声明了一个命名变量,这不是一个好结果。顺便说一句,我使用的是改装和GSON库

编辑:

这里是流程,所以这些键就是我在API上询问的键。例如,我问了一些东西,一些东西,一些东西。数据结果将是

{

"data": [{
        "something_edit1": true
    }, {
        "something_edit2": false
    },
    {
        "something_edit3": false
    }
],

"success": true
}

您可以根据您的条件使用
Json对象
泛型

使用Json对象,您可以检查Json中是否存在密钥

使用泛型,您必须检查您的Pojo是否有 波乔


尝试仅查看此部分中的泛型部分。

您可以根据您的情况使用
Json对象
泛型

使用Json对象,您可以检查Json中是否存在密钥

使用泛型,您必须检查您的Pojo是否有 波乔


尝试仅查看此部分的通用部分。

很难确定,或者您必须在POJO中声明所有可能的字段,或者编写自己的json解析器扩展Gson解析器,或者使用可以转换为json数组、对象和基元的JsonElement,基于该结果,您可以转换回某些特定的pojo

   /**
 * this will convert the whole json into map which you can use to determine the json elements
 *
 * @param json
 */
private void getModelFromJson(JsonObject json) {
    Gson gson = new Gson();
    Map<String, JsonElement> jsonElementMap = gson.fromJson(json.toString(), new TypeToken<Map<String, JsonElement>>() {
    }.getType());
    for (Map.Entry<String, JsonElement> jsonElementEntry : jsonElementMap.entrySet()) {
        if (jsonElementEntry.getValue().isJsonPrimitive()) {
            //json primitives are data types, do something
            //get json boolean
            //you can here also check if json element has some json object or json array or primitives based on that
            //you can convert this to something else after comparison
            if (true) {
                InterestModelResponse response = gson.fromJson(jsonElementEntry.getValue().getAsJsonObject().toString(), InterestModelResponse.class);
                //use your dynamic converted model
            }
        } else {
            //do something else
        }
    }

}
/**
*这将把整个json转换成可以用来确定json元素的映射
*
*@param-json
*/
私有void getModelFromJson(JsonObject json){
Gson Gson=新的Gson();
Map jsonElementMap=gson.fromJson(json.toString(),new-TypeToken()){
}.getType());
对于(Map.Entry jsonElementEntry:jsonElementMap.entrySet()){
if(jsonElementEntry.getValue().isJsonPrimitive()){
//json原语是数据类型,请做些什么
//获取json布尔值
//您还可以在此检查json元素是否具有基于该元素的json对象、json数组或原语
//您可以在比较后将其转换为其他内容
如果(真){
InterestModelResponse response=gson.fromJson(jsonelementry.getValue().getAsJsonObject().toString(),InterestModelResponse.class);
//使用动态转换模型
}
}否则{
//做点别的
}
}
}

很难确定,或者您必须声明POJO中所有可能的字段,或者编写自己的json解析器扩展Gson解析器,或者使用JsonElement将其转换为json数组、对象和原语,根据该结果,您可以转换回某个特定的POJO

   /**
 * this will convert the whole json into map which you can use to determine the json elements
 *
 * @param json
 */
private void getModelFromJson(JsonObject json) {
    Gson gson = new Gson();
    Map<String, JsonElement> jsonElementMap = gson.fromJson(json.toString(), new TypeToken<Map<String, JsonElement>>() {
    }.getType());
    for (Map.Entry<String, JsonElement> jsonElementEntry : jsonElementMap.entrySet()) {
        if (jsonElementEntry.getValue().isJsonPrimitive()) {
            //json primitives are data types, do something
            //get json boolean
            //you can here also check if json element has some json object or json array or primitives based on that
            //you can convert this to something else after comparison
            if (true) {
                InterestModelResponse response = gson.fromJson(jsonElementEntry.getValue().getAsJsonObject().toString(), InterestModelResponse.class);
                //use your dynamic converted model
            }
        } else {
            //do something else
        }
    }

}
/**
*这将把整个json转换成可以用来确定json元素的映射
*
*@param-json
*/
私有void getModelFromJson(JsonObject json){
Gson Gson=新的Gson();
Map jsonElementMap=gson.fromJson(json.toString(),new-TypeToken()){
}.getType());
对于(Map.Entry jsonElementEntry:jsonElementMap.entrySet()){
if(jsonElementEntry.getValue().isJsonPrimitive()){
//json原语是数据类型,请做些什么
//获取json布尔值
//您还可以在此检查json元素是否具有基于该元素的json对象、json数组或原语
//您可以在比较后将其转换为其他内容
如果(真){
InterestModelResponse response=gson.fromJson(jsonelementry.getValue().getAsJsonObject().toString(),InterestModelResponse.class);
//使用动态转换模型
}
}否则{
//做点别的
}
}
}

2年前,我们做了一个项目,在该项目中,我们必须在使用改造时处理的同一数组中使用不同类型的对象来处理通知数据

这是我们的改装
Creator
课程

class Creator {
    public static FullTeamService newFullTeamService() {
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(FullTeamService.HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(FullTeamService.class);
    }
}
GsonUtils.java
是:

public class GsonUtils {
    private static final Gson sGson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        .registerTypeAdapter(NotificationObject.class, new NotificationDeserializer())
        .create();

   private GsonUtils() {}

   public static Gson get() {
    return sGson;
   }
}
NotificationObject
类似于:

public class NotificationObject {

@SerializedName("ID")
@Expose
private long ID;

@SerializedName("type")
@Expose
private Type type;

@SerializedName("DataObject")
@Expose
private NotificationDataObject dataObject;

public void setDataObject(NotificationDataObject newsFields) {
    dataObject = newsFields;
}

@SuppressWarnings("unchecked")
public <T> T getDataObject() {
    return (T) dataObject;
}
public enum Type {
    @SerializedName("0")
    CHAT_MESSAGE,
    @SerializedName("10")
    GAME_APPLICATION,
    @SerializedName("20")
    GAME_APPLICATION_RESPONSE,
    @SerializedName("30")
    GAME_INVITE....
}
}
最后,NotificationDeserializer类似于:

public class NotificationDeserializer implements JsonDeserializer<NotificationObject> {
@Override
public NotificationObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject itemBean = json.getAsJsonObject();
    final NotificationObject object = GsonUtils.getSimpleGson().fromJson(itemBean, NotificationObject.class);
    switch (object.getType()) {
        case CHAT_MESSAGE:
            break;
        case GAME_APPLICATION:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationNotification.class));
            break;
        case GAME_APPLICATION_RESPONSE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationResponseNotification.class));
            break;
        case GAME_INVITE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameInviteNotification.class));
            break;
}
    return object;
}
}
公共类NotificationDeserializer实现JsonDeserializer{
@凌驾
公共NotificationObject反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext)引发JsonParseException{
final JsonObject itemBean=json.getAsJsonObject();
final NotificationObject object=GsonUtils.getSimpleGson().fromJson(itemBean,NotificationObject.class);
开关(object.getType()){
案例聊天室信息:
打破
案例游戏应用:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get(“DataObject”).getAsJsonObject(),
GameApplicationNotification.class);
打破
案例游戏\应用\响应:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get(“DataObject”).getAsJsonObject(),
GameApplicationResponseNotification.class);
打破
案例游戏邀请:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get(“DataObject”).getAsJsonObject(),
gamenotification.class));
打破
}
返回对象;
}
}
快乐编码


任何查询都将受到欢迎……

2年前,我们做了一个项目,在该项目中,我们必须在使用改型时处理同一数组中不同类型对象的通知数据

这是我们的改装
Creator
课程

class Creator {
    public static FullTeamService newFullTeamService() {
        final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

        final Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(FullTeamService.HOST)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(FullTeamService.class);
    }
}
GsonUtils.java
是:

public class GsonUtils {
    private static final Gson sGson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
        .registerTypeAdapter(NotificationObject.class, new NotificationDeserializer())
        .create();

   private GsonUtils() {}

   public static Gson get() {
    return sGson;
   }
}
NotificationObject
类似于:

public class NotificationObject {

@SerializedName("ID")
@Expose
private long ID;

@SerializedName("type")
@Expose
private Type type;

@SerializedName("DataObject")
@Expose
private NotificationDataObject dataObject;

public void setDataObject(NotificationDataObject newsFields) {
    dataObject = newsFields;
}

@SuppressWarnings("unchecked")
public <T> T getDataObject() {
    return (T) dataObject;
}
public enum Type {
    @SerializedName("0")
    CHAT_MESSAGE,
    @SerializedName("10")
    GAME_APPLICATION,
    @SerializedName("20")
    GAME_APPLICATION_RESPONSE,
    @SerializedName("30")
    GAME_INVITE....
}
}
最后,NotificationDeserializer类似于:

public class NotificationDeserializer implements JsonDeserializer<NotificationObject> {
@Override
public NotificationObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    final JsonObject itemBean = json.getAsJsonObject();
    final NotificationObject object = GsonUtils.getSimpleGson().fromJson(itemBean, NotificationObject.class);
    switch (object.getType()) {
        case CHAT_MESSAGE:
            break;
        case GAME_APPLICATION:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationNotification.class));
            break;
        case GAME_APPLICATION_RESPONSE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameApplicationResponseNotification.class));
            break;
        case GAME_INVITE:
            object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
                    GameInviteNotification.class));
            break;
}
    return object;
}
}
公共类NotificationDeserializer实现JsonDeserializer{
@凌驾
public NotificationObject反序列化(JsonElement json,类型typeOfT,JsonDeserializationContext contex