簡體   English   中英

在不知道值格式的情況下使用GSON解析JSON

[英]Parsing JSON with GSON without knowing the value format

嗨,大家好,我有一個像這樣的api,您可以看到我有一個metaData數組,並且數組中的所有項目都有一個Integer ID和一個字符串鍵,但是它們的值都不相同,我在Object中定義了值,但是我有一個錯誤,這是錯誤

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 3871 path $[0].meta_data

這是我的POJO課

Pojo(產品)主班

@SerializedName("meta_data")
@Expose
private MetaDatum metaData;

這是MetaDatum類

public class MetaDatum implements Parcelable {

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("key")
@Expose
private String key;
@SerializedName("value")
@Expose
private Object value;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getKey() {
    return key;
}

public void setKey(String key) {
    this.key = key;
}

public Object getValue() {
    return value;
}

public void setValue(Object value) {
    this.value = value;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeValue(this.id);
    dest.writeString(this.key);
    dest.writeParcelable((Parcelable) this.value, flags);
}

public MetaDatum() {
}

protected MetaDatum(Parcel in) {
    this.id = (Integer) in.readValue(Integer.class.getClassLoader());
    this.key = in.readString();
    this.value = in.readParcelable(Object.class.getClassLoader());
}

public static final Parcelable.Creator<MetaDatum> CREATOR = new Parcelable.Creator<MetaDatum>() {
    @Override
    public MetaDatum createFromParcel(Parcel source) {
        return new MetaDatum(source);
    }

    @Override
    public MetaDatum[] newArray(int size) {
        return new MetaDatum[size];
    }
};
}

您的meta_data是數組而不是對象

meta_data": [
      {
        "id": 3281,
        "key": "_vc_post_settings",
        "value": {
          "vc_grid_id": []
        }
      ]

所以使用清單

private List<MetaDatum> metaData;

使用robopojo puligns或http://www.jsonschema2pojo.org/為您的json數據創建所有pojo類

之后,使改造對象定義基本URL和其他內容...

public class ApiClient {
private final static String BASE_URL = "https://goorab.com/wp-json/wc/v2/";

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}
}

並制作API調用界面。

public interface ApiInterface {
@GET("products")
Call<ResponseData> getdata(@Query("consumer_key") String key);

}

之后調用如下活動或片段。

ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<ResponseData> responseCall = apiInterface.getdata("pass key");
    responseCall.enqueue(new Callback<ResponseData>() {
        @Override
        public void onResponse(Call<ResponseData> call, retrofit2.Response<ResponseData> response) {
            if (response.isSuccessful() && response.body() != null && response != null) {
                Toast.makeText(getApplicationContext(), "GetData" + response.body().getLanguage(), Toast.LENGTH_SHORT).show();


            }
        }

        @Override
        public void onFailure(Call<ResponseData> call, Throwable t) {
            Log.d("Errror", t.getMessage());
        }
    });

並確保pojo類均有效。

除必須轉義的字符外,所有Unicode字符都可以放在引號內:引號,反斜線和控制字符(U + 0000至U + 001F)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM