2017-02-15 59 views
1

我想將一個JSON對象(來自一個API)反序列化到它們各自的Java對象中。我正在使用gson庫(對於Android)。事情是,我已經嘗試了好幾天,並且沒有運氣測試了很多種選擇,所以我真的很感謝這一點的幫助。用Gson反序列化一個複雜的JSON(幾個嵌套元素)

*檢索到JSON。所有我從API收到JSONs遵循以下結構:

{ 
"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 */ 
    } 
} 

由於所有JSONs的結構收到有異曲同工之處,我想利用這個優勢並擴展對象從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。我真的很感謝任何幫助。

+0

很難映射提供JSON和頭部的映射。你可能錯過了別的東西補充?.. –

+0

@breo你檢查了我的答案? – Krish

回答

1

這是我與響應級的解決方案,

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 ; 

     } 
    } 

使用這個類使用自定義TypeAdapter沿着GSON。然後將兩個表工作,物體響應。

一個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(); 
+0

對不起延遲迴復!非常感謝你的回答!我可以從那裏跟進。 – breo

相關問題