簡體   English   中英

我如何像Javascript對象一樣從Java發送對象?

[英]How i send a object from Java like a Javascript object?

我有一個應用程序Angular 7前端,Android移動版和Laravel后端。 我在Angular 7中發送了一個可以在Laravel上正常工作的對象

{
  "mov_entry_id": 72507,
  "limitHour": "02/07/2019 13:40:27",
  "plate": null,
  "mov_vehicle_id": 1,
  "mov_vehicle_name": "Carro",
  "value": "8.00",
  "mov_area_id": 7,
  "mov_area_name": "AB",
  "mov_user_id": 1,
  "validated": "N",
  "updated_at": "02/07/2019 13:20:27",
  "mov_entry_ean13": "7800000725070",
  "created_at": "02/07/2019 13:20:27"
}

我正在發送一個從angular到laravel的post方法,這是接收此對象的后端部分

           $entryObj = $request->input('entry');
           $userid = $request->input('userid');
           $hourValue = 0;
           $validatedDate;

           $response["success"] = 1;
           $response["message"] = "Entrada validada com blabla";
           $response['entryObj'] = $entryObj;
           $response['mov_entry_ean13'] = $entryObj["mov_entry_ean13"];
           return $response;

我在“ $ request-> input('entry');”中得到對象 在這一部分中,我想訪問像這樣的對象$ entryObj [“ mov_entry_ean13”]; ,當我向大家展示Json隨Angular 7一起發送時,我的Laravel應用程序訪問權限很好,但是我的問題出在Android上。

當我在Android中使用Java時,我試圖使對象看起來像javascript一樣,但是沒有成功,我嘗試了JsonObject,JsonElement和Map,這是我的Retrofit API:

@FormUrlEncoded
    @POST("/api/validateentrymobi")
    public Call<JsonObject> validateTicket(
            @Field("entry")  JsonObject entry,
            @Field("userid") String user_id
    );

當我使用此錯誤消息“非法字符串偏移量“ mov_entry_ean13”“時 ,就像我發送的對象有問題,這是來自Java的對象

{"mov_entry_id":72507,"plate":null,"mov_vehicle_id":1,"mov_vehicle_name":"Carro","value":"8.00","mov_area_id":7,"mov_area_name":"AB","mov_user_id":1,"validated":"N","mov_entry_ean13":"7800000725070","created_at":"02/07/2019 13:20:27","updated_at":"02/07/2019 13:20:27","validated_date":"2019-07-02 13:40:27"}

我做錯了什么?

您需要創建一個POJO並設置一個JSON轉換器供Retrofit使用。

設置改造

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create()) // this requires implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
        .build()

創建一個用Gson注釋的POJO類

// this will act as the top level json object {}
class MyBody {
    @SerializedName("mov_entry_id")
    int movEntryId;

    // write your fields here
}

將POJO用作主體以進行改裝

// you don't need the form unless your backend requires it
    @POST("/api/validateentrymobi")
    public Call<ResponseBody> validateTicket( // @NOTE the return type, you can create a POJO class similar to how I created MyBody and replace ResponseBody with it. But ResponseBody should work.
        @Body MyBody myBody
    );

暫無
暫無

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

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