我是json解析的新手,最近我一直在使用改造从服务器中检索数据,如下所示:

[
    [ time, low, high, open, close, volume ],
    [ 1415398768, 0.32, 4.2, 0.35, 4.2, 12.3 ],
    ...
]



我的对象类是

import java.util.List;


public class cbProducts {
    List<String> data;

    public cbProducts(List<String> data) {
        this.data = data;

    }
}


我的介面

public interface cbClient {

    @GET("/products/BTC-USD/candles")
    Call<List<cbProducts>> Authenticate(
            @Header("CB-ACCESS-KEY") String key,
            @Header("CB-ACCESS-SIGN") String sign,
            @Header("CB-ACCESS-TIMESTAMP") String timestamp,
            @Header("CB-ACCESS-PASSPHRASE") String passphrase,
            @Query("start") String startTime,
            @Query("end") String endTime,
            @Query("granularity") String granularity
    ) ;

}


我的回应

Retrofit.Builder builder = new Retrofit.Builder()
                    .baseUrl("https://api.pro.coinbase.com")
                    .addConverterFactory(GsonConverterFactory.create());
            Retrofit retrofit = builder.build();
            cbClient client = retrofit.create(cbClient.class);

            Call<List<cbProducts>> call = client.Authenticate("XXXX","XXXX","XXXX","XXXX","XXXX","XXXX","XXXX");

            call.enqueue(new Callback<List<cbProducts>>() {
                @Override
                public void onResponse(Call<List<cbProducts>> call, Response<List<cbProducts>> response) {
                    //cbProducts[] cbP = new Gson().fromJson(String.valueOf(response), (Type) cbProducts[].class);
                    Gson gson = new Gson();
                    cbProducts cb = gson.fromJson(String.valueOf(response),cbProducts.class);
                    Log.d("MESSAGE",cb.toString());
                    Log.d("MESSAGE", String.valueOf(response.code()));


                }

                @Override
                public void onFailure(Call<List<cbProducts>> call, Throwable t) {
                    Log.d("MESSAGE", t.getMessage());

                }
            });


和我不断收到读取Expected BEGIN_OBJECT but was BEGIN_ARRAY相同的错误。我不明白为什么我在尝试接收数组时java期望Json对象。任何帮助将不胜感激。

最佳答案

您无需再次解析响应,请调用response.body()以获得List<cbProducts>删除此响应

Gson gson = new Gson();
cbProducts cb = gson.fromJson(String.valueOf(response),cbProducts.class);
Log.d("MESSAGE",cb.toString());
Log.d("MESSAGE", String.valueOf(response.code()));

和使用
List<cbProducts> products = response.body();

关于java - GSON“预期为BEGIN_OBJECT,但为BEGIN_ARRAY”错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62294129/

10-11 01:21