如何使用 retrofit 2 检索 json 多层数据?

问题描述 投票:0回答:1

我需要从警察数据库中检索车辆数据,API返回一个多级JSON,即使我创建了正确的查询链接,也返回null,我得到200response代码(所以连接已建立)。谁能帮我解决这个问题?

{
    "BillingAccount": {
        "AccountType": "Trial",
        "AccountBalance": 999.99,
        "TransactionCost": 999.99,
        "ExtraInformation": {}
    },
    "Request": {
        "RequestGuid": "7694b77d-fc1b-45e1-b141-7edb5aa83123",
        "PackageId": "9b88a11d-cae4-4855-b904-a43744951107",
        "PackageVersion": 2,
        "ResponseVersion": 2,
        "DataKeys": {
            "Vrm": "AB02HAY"
        }
    },
    "Response": {
        "StatusCode": "Success",
        "StatusMessage": "Success",
        "StatusInformation": {
            "Lookup": {
                "StatusCode": "Success",
                "StatusMessage": "Success",
                "AdviceTextList": []
            }
        },
        "DataItems": {
            "TechnicalDetails": {5 items},
            "ClassificationDetails": {2 items},
            "VehicleStatus": {
                "MotVed": {
                    "VedRate": {
                        "FirstYear": {
                             "SixMonth": 101.75,
                             "TwelveMonth": 185
                        },
                        "PremiumVehicle": {
                            "YearTwoToSix": {
                                  "TwelveMonth": null,
                                  "SixMonth": null
                            }
                        },
                        "Standard": {
                            "SixMonth": 110,
                            "TwelveMonth": 205
                        }
                   },
                   "VedCo2Emissions": 156,
                   "MotDue": null,
                   "VedBand": "G",
                   "VedCo2Band": "G",
                   "TaxDue": null,
                   "Message": null,
                   "VehicleStatus": null
                }
            },
            "VehicleHistory": {11 items},
            "VehicleRegistration": {40 items},
            "SmmtDetails": {21 items}
        }
    }
}

到目前为止,我已经创建了一个接口。

package com.example.carcare;

import java.util.List;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

public interface DvlaApi {

    String v = "2";
    String api_nullitems = "1" ;
    String auth_apikey = "b5d7757f-da24-47e5-8cec-03caa133cf6c";
    String key_VRM = "";
    String user_tag= "";




    @GET("api/datapackage/VehicleData")
    Call<Vehicle> getProducts(@Query("v") String v,
                                    @Query("api_nullitems") String api_nullitems,
                                    @Query("auth_apikey") String auth_apikey,
                                    @Query("user_tag") String user_tag,
                                    @Query("key_VRM") String key_VRM);


}

一个对象类。

package com.example.carcare;

public class Vehicle
{
   private String make;

    public Vehicle(String make) {
        this.make = make;
    }

    String getMake() {
        return make;
    }
}

而在MainActivity中,我需要检索车辆数据。

package com.example.carcare;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class MainActivity extends AppCompatActivity {

    public TextInputEditText ti_licence;
    TextView tv_result, tv_code_result;
    Button search;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ti_licence = findViewById(R.id.ti_licencePlate);
        tv_result = findViewById(R.id.tv_result);
        tv_code_result = findViewById(R.id.tv_code_result);
        search = findViewById(R.id.search);

        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getData();


            }


        });
    }
    public void getData(){

        String licencePlate = String.valueOf(ti_licence.getText());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://uk1.ukvehicledata.co.uk/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        DvlaApi service = retrofit.create(DvlaApi.class);

        Call<Vehicle> call = service.getProducts(DvlaApi.v, DvlaApi.api_nullitems, DvlaApi.auth_apikey, DvlaApi.user_tag, licencePlate);

        call.enqueue(new Callback<Vehicle>() {
            @Override
            public void onResponse(Call<Vehicle> call, Response<Vehicle> response) {

                if (!response.isSuccessful()){
                    tv_result.setText("Code: " + response.code());
                    Log.e("content: ", response.body().toString());
                    tv_code_result.setText(response.code());
                    return;
                }

                Vehicle auto = response.body();


                assert auto != null;
                String make = auto.getMake();
                tv_result.setText(String.valueOf(make));


            }

            @Override
            public void onFailure(Call<Vehicle> call, Throwable t) {

                tv_result.setText(t.getMessage());
                tv_code_result.setText(t.getMessage());

            }
        });
    }
}
android api retrofit2
1个回答
0
投票

你需要将返回的数据完全以相同的层次结构和相同的字段名进行响应,除非你想使用@SerializedName符号。这就是你的Response Model类应该如何让GSON Deserialization发生。

data class ReturnData(
    val BillingAccount: BillingAccount = BillingAccount(),
    val Request: Request = Request(),
    val Response: Response = Response()
) {
    data class BillingAccount(
        val AccountBalance: Double = 0.0,
        val AccountType: String = "",
        val ExtraInformation: ExtraInformation = ExtraInformation(),
        val TransactionCost: Double = 0.0
    ) {
        class ExtraInformation(
        )
    }

    data class Request(
        val DataKeys: DataKeys = DataKeys(),
        val PackageId: String = "",
        val PackageVersion: Int = 0,
        val RequestGuid: String = "",
        val ResponseVersion: Int = 0
    ) {
        data class DataKeys(
            val Vrm: String = ""
        )
    }

    data class Response(
        val DataItems: DataItems = DataItems(),
        val StatusCode: String = "",
        val StatusInformation: StatusInformation = StatusInformation(),
        val StatusMessage: String = ""
    ) {
        data class DataItems(
            val ClassificationDetails: ClassificationDetails = ClassificationDetails(),
            val SmmtDetails: SmmtDetails = SmmtDetails(),
            val TechnicalDetails: TechnicalDetails = TechnicalDetails(),
            val VehicleHistory: VehicleHistory = VehicleHistory(),
            val VehicleRegistration: VehicleRegistration = VehicleRegistration(),
            val VehicleStatus: VehicleStatus = VehicleStatus()
        ) {
            class ClassificationDetails(
            )

            class SmmtDetails(
            )

            class TechnicalDetails(
            )

            class VehicleHistory(
            )

            class VehicleRegistration(
            )

            data class VehicleStatus(
                val MotVed: MotVed = MotVed()
            ) {
                data class MotVed(
                    val Message: Any = Any(),
                    val MotDue: Any = Any(),
                    val TaxDue: Any = Any(),
                    val VedBand: String = "",
                    val VedCo2Band: String = "",
                    val VedCo2Emissions: Int = 0,
                    val VedRate: VedRate = VedRate(),
                    val VehicleStatus: Any = Any()
                ) {
                    data class VedRate(
                        val FirstYear: FirstYear = FirstYear(),
                        val PremiumVehicle: PremiumVehicle = PremiumVehicle(),
                        val Standard: Standard = Standard()
                    ) {
                        data class FirstYear(
                            val SixMonth: Double = 0.0,
                            val TwelveMonth: Int = 0
                        )

                        data class PremiumVehicle(
                            val YearTwoToSix: YearTwoToSix = YearTwoToSix()
                        ) {
                            data class YearTwoToSix(
                                val SixMonth: Any = Any(),
                                val TwelveMonth: Any = Any()
                            )
                        }

                        data class Standard(
                            val SixMonth: Int = 0,
                            val TwelveMonth: Int = 0
                        )
                    }
                }
            }
        }

        data class StatusInformation(
            val Lookup: Lookup = Lookup()
        ) {
            data class Lookup(
                val AdviceTextList: List<Any> = listOf(),
                val StatusCode: String = "",
                val StatusMessage: String = ""
            )
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.