与gson的复杂JSON(几个嵌套元素)进行挑选



我试图将一个json对象(来自API)估算为其各自的Java对象。我正在使用GSON库(用于Android)。问题是我已经尝试了几天,并在没有运气的情况下测试了多个选择,所以我真的很感谢您对此的帮助。

*JSON检索。我从API中收到的所有JSON遵循以下结构:

{
"status_code": 200,
"status_message": "Here the status message",
"result": {
    "success": true,
    "internalStatusCall": 1,
    "response": 
            /* Can be a JSON object or a JSON array of objects    */   
    }
}

由于收到的所有JSON的结构都是相似的,因此我想利用这一点,并将对象扩展到JSON映射。

我会想到:

public class TABaseObject {
@SerializedName("status_code")
protected int status_code;
@SerializedName("status_message")
protected String status_message;
protected String type;
public TABaseObject(int status_code, String status_message, String type) {
    this.status_code = status_code;
    this.status_message = status_message;
    this.type = type;
}
}

从这个对象延伸,内部对象将是:

public class TAResultObject extends TABaseObject{
@SerializedName("exito")
protected boolean exito;
@SerializedName("codigoEstado")
protected int codigoEstado;
public TAResultObject(int status_code, String status_message, boolean exito, int codigoEstado) {
    super(status_code, status_message, "resultado");
    this.exito = exito;
    this.codigoEstado = codigoEstado;
}
@Override
public String toString() {
    return super.toString() + " ////// " + "TAResultObject{" +
            "exito=" + exito +
            ", codigoEstado=" + codigoEstado +
            '}';
}

从这个其他对象中,我将tareSultObject扩展到对应对象。

我尝试了几种避免的方法(typeadapterfactory,runtimetypeadapterfactory等),没有运气。

是否有任何策略能够对上述JSON进行挑选。我真的很感谢您对此的任何帮助。

这是我的解决方案,

import java.util.List;
import java.util.Map;
import com.google.gson.annotations.SerializedName;
    public class TAObject {
        @SerializedName("status_code")
        Integer status_code ;
        @SerializedName("status_message")
        String status_message ;
        @SerializedName("result")
        Result result ; 
        public class Result {
            @SerializedName("success")
            Boolean success ;
            @SerializedName("internalStatusCall")
            Integer internalStatusCall ;
            @SerializedName("response")
            List<Map> response ;
        }
    }

使用此类以及GSON的自定义Typeadapter。然后它将适用于列表和对象响应。

arrayadapter类

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

 class ArrayAdapter<T> extends TypeAdapter<List<T>> {
    private Class<T> adapterclass;
    public ArrayAdapter(Class<T> adapterclass) {
        this.adapterclass = adapterclass;
    }
    @Override
    public List<T> read(JsonReader reader) throws IOException {
        List<T> list = new ArrayList<T>();
        Gson gson = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();
        final JsonToken token = reader.peek();
        System.out.println(token);
        // Handling of Scenario 2( Check JavaDoc for the class) :
        if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
                token == JsonToken.BOOLEAN) {
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_OBJECT) {
            // Handling of Scenario 1(Check JavaDoc for the class) :
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            while (reader.hasNext()) {
                @SuppressWarnings("unchecked")
                T inning = (T) gson.fromJson(reader, adapterclass);
                list.add(inning);
            }
            reader.endArray();
        }
        return list;
    }
    @Override
    public void write(JsonWriter writer, List<T> value) throws IOException {
    }

}

arrayadapterFactory类

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
public class ArrayAdapterFactory implements TypeAdapterFactory {
    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type)
    {
        TypeAdapter<T> typeAdapter = null;
        try {
            if (type.getRawType() == List.class || type.getRawType() == ArrayList.class) {
                typeAdapter = new ArrayAdapter(
                        (Class) ((ParameterizedType) type.getType())
                                .getActualTypeArguments()[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return typeAdapter;
    }
}

并这样注册适配器工厂,

Gson gson  = new GsonBuilder().registerTypeAdapterFactory(new ArrayAdapterFactory()).create();

最新更新