GVKun编程网logo

java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY

1

本篇文章给大家谈谈java.lang.IllegalStateException:应为BEGIN_OBJECT,但在第1行第13571列处为BEGINretrofit_ARRAY,同时本文还将给你拓展

本篇文章给大家谈谈java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY,同时本文还将给你拓展Andorid Studio java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT、Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $、Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ java.lang.String java.lang.Object.toString()”、API.java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 56 列处为 STRING等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY

java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY

如何解决java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY

我根据这里的答案更正了我的代码 Retrofit Expected BEGIN_OBJECT but was BEGIN_ARRAY

但我仍然遇到同样的错误。

我使用的 api 是 wordpress。

这是我的 json 响应示例

[
{
    "id": 5095,"parent_id": 0,"number": "5095","order_key": "wc_order_q7QgiKvemzxBd","created_via": "checkout","version": "5.0.0","status": "processing","currency": "USD" 
 },{
    "id": 5094,"parent_id": 5090,"number": "5094","order_key": "wc_order_PeUZBs1eRRgHC","created_via": "dokan","currency": "USD"
 }
]

ApiInterface 方法:

 @Headers({"Content-Type: application/json"})
@GET("wp-json/wc-analytics/orders")
Call<List<OrdersModel>> getAllOrdersWuCo();

我是这么称呼它的

 Call<List<OrdersModel>> allOrdersWuCo = apiInterfaceTwo.getAllOrdersWuCo();
    allOrdersWuCo.enqueue(new Callback<List<OrdersModel>>() {
        @Override
        public void onResponse(Call<List<OrdersModel>> call,Response<List<OrdersModel>> response) {
            List<OrdersModel> list = response.body();

        }

        @Override
        public void onFailure(Call<List<OrdersModel>> call,Throwable t) {
            String message = t.getMessage(); 
        }
    }); 

OrdersModel.java 这是我的订单模型类 我已经发布了一些订单模型类,因为它太大了:

public class OrdersModel {

@Serializedname("id")
@Expose
private Integer id;
@Serializedname("parent_id")
@Expose
private Integer parentId;
@Serializedname("number")
@Expose
private String number;
@Serializedname("order_key")
@Expose
private String orderKey;
@Serializedname("created_via")
@Expose
private String createdVia;
@Serializedname("version")
@Expose
private String version;
@Serializedname("status")
@Expose
private String status;
@Serializedname("currency")
@Expose
private String currency;

public Integer getId() {
    return id;
}

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

public Integer getParentId() {
    return parentId;
}

public void setParentId(Integer parentId) {
    this.parentId = parentId;
}

public String getNumber() {
    return number;
}

public void setNumber(String number) {
    this.number = number;
}

public String getorderKey() {
    return orderKey;
}

public void setorderKey(String orderKey) {
    this.orderKey = orderKey;
}

public String getCreatedVia() {
    return createdVia;
}

public void setCreatedVia(String createdVia) {
    this.createdVia = createdVia;
}

public String getVersion() {
    return version;
}

public void setVersion(String version) {
    this.version = version;
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

public String getCurrency() {
    return currency;
}

public void setCurrency(String currency) {
    this.currency = currency;
}
}

Andorid Studio java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

Andorid Studio java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

如何解决Andorid Studio java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT

我知道这不是关于此错误的第一个问题。我到处寻找答案,但找不到解决方案。当我运行代码时,我收到此异常;

java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $

主要活动

public class MainActivity extends AppCompatActivity {
    ArrayList<Doviz> dovizs;

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

        Retrofit retrofit= new Retrofit.Builder()
                .baseUrl("https://finans.truncgil.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        DovizApi dovizApi = retrofit.create(DovizApi.class);

        Call<List<Doviz>> call = dovizApi.getDoviz();

      

        call.enqueue(new Callback<List<Doviz>>() {

            @Override
            public void onResponse(Call<List<Doviz>> call,Response<List<Doviz>> response) {
                System.out.println("deneme");
                List<Doviz> responseList= response.body();
                dovizs = new ArrayList<>(responseList);
                System.out.println(dovizs.get(0).USD);

            }

            @Override
            public void onFailure(Call<List<Doviz>> call,Throwable t) {
                System.out.println(t.fillInStackTrace());
            }
        });
    }
}

Java 类

public class Doviz {

    @Serializedname("Buying")
    public String USD;

}

界面

public interface DovizApi {
    @GET("today.json")
    Call<List<Doviz>> getDoviz();
}

我使用的列表 https://finans.truncgil.com/v3/today.json

我已经处理这个问题好几天了。希望能解决

解决方法

发生了什么?

  • API 响应的根是 JSONObject 而不是 JSONArray。
  • API URL 中缺少 v3。

解决方案

更新界面

public interface DovizApi {
    @GET("v3/today.json")
    Call<HashMap<String,Object>> getDoviz();
}

更新响应模型(Doviz)

public class Doviz {
   @SerializedName("Buying")
   public String buying;

   // Similarly you can add other keys here
}

更新改造调用

Call<HashMap<String,Object>> call = dovizApi.getDoviz();
call.enqueue(new Callback<HashMap<String,Object>>() {

        @Override
        public void onResponse(Call<HashMap<String,Object>> call,Response<HashMap<String,Object>> response) {
            HashMap<String,Object> responseModel = response.body();

            // Iterate all the currencies
            for (Map.Entry<String,Object> entry : responseModel.entrySet())
                if(entry.getValue() instanceof LinkedTreeMap) { // Since the first element is of type String i.e. "Update_Date"
                    Doviz doviz = new Gson().fromJson(new Gson().toJson(((LinkedTreeMap<String,Object>) entry.getValue())),Doviz.class);
                    System.out.println("Currency = " + entry.getKey() +
                                     ",Buying = " + doviz.buying);
                }
        }

        @Override
        public void onFailure(Call<HashMap<String,Throwable t) {
            System.out.println(t.fillInStackTrace());
        }
    });
,

检查点

  1. 类型

Json 如下图

{
   "Update_Date":"2021-05-12 16:00:01","USD":{
      "Buying":"8,3681","Type":"Currency","Selling":"8,3735","Change":"%1,13"
   },...
}

它不是 <List>USD 是 json 中的关键之一

所以 Call<List<Doviz>> 应该更改为 Call<Doviz>

  1. DTO (Doviz)

您可能需要 BuyingUSD 值。 你是 DTO(Doviz) 应该拥有像这样的另一个 DTO 的财产

  class Doviz {
        @SerializedName("USD")
        CurrencyInfo usd;
       
        // else like this
        @SerializedName("EUR")
        CurrencyInfo eur;

        //...
  }

  class CurrencyInfo {
        //if Path(/v3) included
        @SerializedName("Buying")
        String buying;

        //if Path (/v3) not included 
        @SerializedName("Alış")
        String _buying;

       // else.. 
 }

interface DovizApi{
        @GET("/v3/today.json")
        fun getEnDoviz(): Call<Doviz>
}
Call<Doviz> call = dovizApi.getDoviz();
call.enqueue(new Callback<Doviz>(){
            @Override
            public void onResponse(Call<Doviz> call,Response<Doviz>response){
                Doviz doviz = response.body();
                CurrencyInfo info = doviz.getUsd();
                System.out.println(info.getBuying());
            }
..
}

效果很好。

Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $

Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $

如何解决Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $

我无法从服务器获取 int :( 谢谢指导

Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $

服务器代码:

  1. <?PHP
  2. require(''con.PHP'');
  3. $user_email=$_REQUEST[''user_email''];
  4. $sql = "SELECT SUM(add_pay) AS sum FROM Tbl_tarakonesh WHERE user_email = ''$user_email''";
  5. $result=MysqLi_query($con,$sql);
  6. $response=array();
  7. $row=MysqLi_fetch_array($result);
  8. $jam=$row[''sum''];
  9. echo $jam;
  10. MysqLi_close($con);
  11. ?>

  1. public class Model_kol
  2. {
  3. @Serializedname("jam")
  4. private int jam;
  5. public int getJam() {
  6. return jam;
  7. }
  8. }

  1. public interface MyService {
  2. @GET("show_kol_tarakonesh.PHP")
  3. Call<Model_kol> reg(@Query("user_email") String email);
  4. }

onActivity :

  1. apiInterface = apiclient_Kol.getapiclient().create(MyService.class);
  2. Call<Model_kol> call = this.apiInterface.reg(hw_information.check_hq("tx_email"));
  3. call.enqueue(new Callback<Model_kol>() {
  4. @Override
  5. public void onResponse(Call<Model_kol> call,Response<Model_kol> response) {
  6. // Toast.makeText(getContext().getApplicationContext(),"OK :))",LENGTH_LONG).show();
  7. Toast.makeText(getContext().getApplicationContext(),response.body().getJam()+"",LENGTH_LONG).show();
  8. }
  9. @Override
  10. public void onFailure(Call<Model_kol> call,Throwable t) {
  11. Toast.makeText(getContext().getApplicationContext(),"Failure" + "/n" + t.toString(),LENGTH_LONG).show();
  12. }
  13. });

Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ java.lang.String java.lang.Object.toString()”

Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ java.lang.String java.lang.Object.toString()”

面对我正在使用的练习应用程序的问题。我面临与toString方法有关的NullPointerException问题。作为android应用程序开发的新手,即使经过研究,我也不确定确切的原因。因此,我要求一个更熟悉堆栈跟踪的人来帮助我。

注意:当我单击列表视图条目以访问日记条目的编辑页面时,将发生错误。但是,它似乎根本没有进入编辑页面。

在下面,您将找到我的活动代码及其堆栈跟踪。

活动代码:

import android.app.AlertDialog;import android.content.DialogInterface;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.content.Intent;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.EditText;import android.widget.ListView;import android.widget.TextView;import android.widget.Toast;import java.util.ArrayList;public class ViewDiaryEntries extends AppCompatActivity {// Database HelperMyDBHandler db;// ListviewListView data_list;// Test varpublic final static String KEY_EXTRA_DATA_ID = "KEY_EXTRA_DATA_ID";@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_view_diary_entries);    db = new MyDBHandler(this);    // Displays the database items.    displayItems();}// To display items in the listview.public void displayItems(){    // To display items in a listview.    ArrayList db_data_list = db.getDiaryDBDataList();    ArrayAdapter listAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, db_data_list);    // Set the adapter for the listview    data_list = (ListView) findViewById(R.id.dataListView);    data_list.setAdapter(listAdapter);    /* Experiment -------------------------------------------------------------*/    data_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {        @Override        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            // Selected item store            String selectedEntry = ((TextView) view).getText().toString();            // Test for regular expression            String[] listViewItemSplit = selectedEntry.split(" - ");            String listViewItempt1 = listViewItemSplit[0]; // For date and time            //String listViewItempt2 = listViewItemSplit[1]; // For save file name            //Toast.makeText(ViewDiaryEntries.this, listViewItempt1, Toast.LENGTH_LONG).show();            if(listViewItempt1.equals("")){                Toast.makeText(ViewDiaryEntries.this, "Error. Unable to detect entry ID.", Toast.LENGTH_LONG).show();            }            else{                // Pass on the data:                Intent editEntry = new Intent(ViewDiaryEntries.this, editdiaryentry.class);                editEntry.putExtra(KEY_EXTRA_DATA_ID, listViewItempt1);                startActivity(editEntry);            }        }    });}// For the go back button.public void viewdiarytoinitialdiary_backbutt(View v){    // Create and start new intent going back ot main page.    Intent main_page = new Intent(ViewDiaryEntries.this, User_Main_Menu_Options.class);    main_page.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    startActivity(main_page);}// For the about button.public void viewdiarypage_directionabout_butt(View v){    // Create an alert dialog    final AlertDialog.Builder about_page_dialog = new AlertDialog.Builder(ViewDiaryEntries.this);    about_page_dialog.setTitle("About This Page:");    // Inputs values for the dialog message.    final String dialog_message = "This page will show you any saved diary entries you''ve.\n\n To edit an entry, do the following: \n\n- Take note of the Entry ID# (first value on entry display) \n- Type it in the number box at the bottom. \n- Press Edit Record icon next to number box, and wait for it to load.";    about_page_dialog.setMessage(dialog_message);    about_page_dialog.setPositiveButton("Got it!", new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialog, int which) {            // Closes the dialog.            dialog.cancel();        }    });    // Shows the dialog.    about_page_dialog.show();}// Main menu button.public void viewDiaryEntriesMainMenushortcut_butt(View v){    // Creates main menu alert dialog.    AlertDialog.Builder mainMenu_Dialog = new AlertDialog.Builder(this);    mainMenu_Dialog.setIcon(R.drawable.main_menu_symbol);    mainMenu_Dialog.setTitle("Main Menu");    // Creates array adapter with items to fill the menu with.    final ArrayAdapter<String> menuItemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);    menuItemsAdapter.add("Home Screen");    menuItemsAdapter.add("Diary");    menuItemsAdapter.add("Tests");    menuItemsAdapter.add("Activity");    menuItemsAdapter.add("Media");    menuItemsAdapter.add("Thought of the Day");    menuItemsAdapter.add("Inspirational Quotes");    menuItemsAdapter.add("Resources");    menuItemsAdapter.add("Settings");    // To close menu.    mainMenu_Dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialog, int which) {            dialog.cancel();        }    });    // To go to appropriate page upon selection.    mainMenu_Dialog.setAdapter(menuItemsAdapter, new DialogInterface.OnClickListener() {        @Override        public void onClick(DialogInterface dialog, int which) {            String selectedItem = menuItemsAdapter.getItem(which);            if(selectedItem.equals("Home Screen")){                // Goes to main menu.                Intent mainMenu = new Intent(ViewDiaryEntries.this, User_Main_Menu_Options.class);                mainMenu.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(mainMenu);            }            else if(selectedItem.equals("Diary")){                // Goes to diary page.                Intent diaryPage = new Intent(ViewDiaryEntries.this, ViewDiaryEntries.class);                diaryPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(diaryPage);            }            else if(selectedItem.equals("Tests")){                // Goes to tests page.                Intent testsPage = new Intent(ViewDiaryEntries.this, TestChoices.class);                testsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(testsPage);            }            else if(selectedItem.equals("Media")){                // Goes to media page.                Intent mediaPage = new Intent(ViewDiaryEntries.this, initialMediaPage.class);                mediaPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(mediaPage);            }            else if(selectedItem.equals("Thought of the Day")){                // Goes to thought of the day page.                Intent thoughtofthedayPage = new Intent(ViewDiaryEntries.this, thoughtQuotes.class);                thoughtofthedayPage.putExtra("quote_or_thought", 2);                thoughtofthedayPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(thoughtofthedayPage);            }            else if(selectedItem.equals("Inspirational Quotes")){                // Goes to inspirational quotes page.                Intent inspirationalquotesPage = new Intent(ViewDiaryEntries.this, thoughtQuotes.class);                inspirationalquotesPage.putExtra("quote_or_thought", 1);                inspirationalquotesPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(inspirationalquotesPage);            }            else if(selectedItem.equals("Settings")){                // Goes to settings page.                Intent settingsPage = new Intent(ViewDiaryEntries.this, settings.class);                settingsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);                startActivity(settingsPage);            }        }    });    mainMenu_Dialog.show();}// For the settings button.public void viewdiarypagelisttoSettings_butt(View v){    // Goes to settings page.    Intent settingsPage = new Intent(ViewDiaryEntries.this, settings.class);    settingsPage.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    startActivity(settingsPage);}// For new entry.public void viewdiarypageaddEntry_butt(View v){    // Opening up the diary add intent.    Intent newdiaryEntry = new Intent(ViewDiaryEntries.this, newdiaryentry.class);    startActivity(newdiaryEntry);}}

这是我看到的堆栈跟踪:

java.lang.NullPointerException: Attempt to invoke virtual method ''java.lang.String java.lang.Object.toString()'' on a null object reference        at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:401)        at android.widget.ArrayAdapter.getView(ArrayAdapter.java:369)        at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:194)        at android.widget.Spinner.onMeasure(Spinner.java:580)        at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:407)        at android.view.View.measure(View.java:18794)        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)        at android.view.View.measure(View.java:18794)        at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1283)        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)        at android.widget.ScrollView.onMeasure(ScrollView.java:340)        at android.view.View.measure(View.java:18794)        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)        at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)        at android.view.View.measure(View.java:18794)        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)        at android.view.View.measure(View.java:18794)        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)        at android.view.View.measure(View.java:18794)        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465)        at android.widget.LinearLayout.measureVertical(LinearLayout.java:748)        at android.widget.LinearLayout.onMeasure(LinearLayout.java:630)        at android.view.View.measure(View.java:18794)        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5951)        at android.widget.FrameLayout.onMeasure(FrameLayout.java:194)        at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2643)        at android.view.View.measure(View.java:18794)        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2100)        at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1216)        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1452)        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)        at android.view.Choreographer.doCallbacks(Choreographer.java:670)        at android.view.Choreographer.doFrame(Choreographer.java:606)        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)        at android.os.Handler.handleCallback(Handler.java:739)        at android.os.Handler.dispatchMessage(Handler.java:95)        at android.os.Looper.loop(Looper.java:148)        at android.app.ActivityThread.main(ActivityThread.java:5417)        at java.lang.reflect.Method.invoke(Native Method)        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

任何对解决方案的帮助将不胜感激。

编辑:

因此,在从数据库和与之交互的活动之间的代码来回浏览之后,我设法使其重新工作。以下是我按确切顺序执行的操作:

  1. 我意识到我有一个日期字段没有接收任何数据,对此进行了纠正。
  2. 清理了项目。
  3. 重新启动Android Studio(基本上停止开发环境的所有操作)。
  4. 从我的开发手机上卸载了该应用。
  5. 重新启动android studio并重新安装该应用程序。
  6. 我以某种方式工作= _ =,是的,这很神奇。

老实说,我不知道哪一步真正解决了它。我猜这是数据库中的日期字段在我没有收到任何数据的同时给我带来了麻烦。

答案1

小编典典

您的阵列中ArrayAdapter至少包含一个条目null。那里不能有空值。

数组被填充,getDiaryDBDataList()所以问题也在那里。

API.java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 56 列处为 STRING

API.java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 56 列处为 STRING

如何解决API.java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 56 列处为 STRING

JSON

  1. {
  2. "status": "success","message": "User Registered Successfully","data": {
  3. "name": "pooja","mobile_no": "8211111111","email": "pooja@gmail.com","referal_id": null,"password": "$2y$10$AaleHI56","created_at": "2021-01-27T09:21:35.056380Z","updated_at": "2021-01-27T09:21:35.056411Z"
  4. }
  5. }

我已经从 jsonschema2pojo 创建了类,并且已经多次验证 json 是否有效,但我仍然收到此错误

为上述 json 创建了两个类 - SignUpResponseSignUpData

  1. public interface RetrofitServicesSignUp {
  2. @FormUrlEncoded
  3. @POST("/api/passenger-register")
  4. Call<SignUpResponse> savePost(
  5. @Field("name") String name,@Field("mobile_no") String mobile_no,@Field("email") String email,@Field("password") String password,@Field("password_confirm") String password_confirm,@Field("referal_id") String referal_id,@Field("device_token") String device_token
  6. // @Field("device_token") String device_token
  7. );
  8. }

主要活动是

  1. protected void onCreate(Bundle savedInstanceState) {
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.sign_up_layout);
  4. mAPISignUpInterfaceService = ApiUtilsSignUp.getAPIService();
  5. username = edtUserName.getText().toString();
  6. password = edtPassword.getText().toString();
  7. phonestringValue = edtPhoneNumber.getText().toString();
  8. conPassword = edtConfirmPassword.getText().toString();
  9. email = edtEmail.getText().toString();
  10. referralcode = edtReferralCode.getText().toString();
  11. btnSignUp.setonClickListener(new View.OnClickListener() {
  12. public void onClick(View v) {
  13. boolean failFlag = false;
  14. stringPhoneNumberlength = edtPhoneNumber.getText().toString().length();
  15. if (edtUserName.getText().toString().trim().length() == 0) {
  16. failFlag = true;
  17. edtUserName.setError("Fill name");
  18. }
  19. //As above have done checking with empty field
  20. if (failFlag == false) {
  21. //none of the edit text is empty so good to go
  22. sendPost(username,phonestringValue,email,password,conPassword,referralcode);
  23. }
  24. }
  25. public void sendPost(String namee,String mobilenumberba,String emaill,String passwordd,String confirmpasswordd,String referalcodee ) {
  26. mAPISignUpInterfaceService.savePost(namee,mobilenumberba,emaill,passwordd,confirmpasswordd,referalcodee,"abcdef").enqueue(new Callback<SignUpResponse>() {
  27. @Override
  28. public void onResponse(Call<SignUpResponse> call,Response<SignUpResponse> response) {
  29. if(response.isSuccessful()) {
  30. SignUpResponse jsonSignUpResponse = response.body();
  31. Log.i(TAG,"Token from JsonResponse: " + jsonSignUpResponse.getStatus());
  32. Log.i(TAG,"Token from JsonResponse: " + jsonSignUpResponse.getMessage());
  33. }
  34. }
  35. @Override
  36. public void onFailure(Call<SignUpResponse> call,Throwable t) {
  37. Log.e(TAG,"Unable to submit post to API."+t.getCause());
  38. }
  39. });
  40. }
  41. });
  42. }

}

注册数据

  1. public class SignUpData {
  2. @Serializedname("name")
  3. @Expose
  4. private String name;
  5. @Serializedname("mobile_no")
  6. @Expose
  7. private String mobileNo;
  8. @Serializedname("email")
  9. @Expose
  10. private String email;
  11. @Serializedname("referal_id")
  12. @Expose
  13. private Object referalId;
  14. @Serializedname("password")
  15. @Expose
  16. private String password;
  17. @Serializedname("created_at")
  18. @Expose
  19. private String createdAt;
  20. @Serializedname("updated_at")
  21. @Expose
  22. private String updatedAt;
  23. public String getName() {
  24. return name;
  25. }
  26. public void setName(String name) {
  27. this.name = name;
  28. }
  29. public String getMobileNo() {
  30. return mobileNo;
  31. }
  32. public void setMobileNo(String mobileNo) {
  33. this.mobileNo = mobileNo;
  34. }
  35. public String getEmail() {
  36. return email;
  37. }
  38. public void setEmail(String email) {
  39. this.email = email;
  40. }
  41. public Object getReferalId() {
  42. return referalId;
  43. }
  44. public void setReferalId(Object referalId) {
  45. this.referalId = referalId;
  46. }
  47. public String getpassword() {
  48. return password;
  49. }
  50. public void setPassword(String password) {
  51. this.password = password;
  52. }
  53. public String getCreatedAt() {
  54. return createdAt;
  55. }
  56. public void setCreatedAt(String createdAt) {
  57. this.createdAt = createdAt;
  58. }
  59. public String getUpdatedAt() {
  60. return updatedAt;
  61. }
  62. public void setUpdatedAt(String updatedAt) {
  63. this.updatedAt = updatedAt;
  64. }
  65. }

注册响应

  1. public class SignUpResponse {
  2. @Serializedname("status")
  3. @Expose
  4. private String status;
  5. @Serializedname("message")
  6. @Expose
  7. private String message;
  8. @Serializedname("data")
  9. @Expose
  10. private SignUpData data;
  11. public String getStatus() {
  12. return status;
  13. }
  14. public void setStatus(String status) {
  15. this.status = status;
  16. }
  17. public String getMessage() {
  18. return message;
  19. }
  20. public void setMessage(String message) {
  21. this.message = message;
  22. }
  23. public SignUpData getData() {
  24. return data;
  25. }
  26. public void setData(SignUpData data) {
  27. this.data = data;
  28. }
  29. }

所以现在 json 是正确的,那么为什么会出现这个错误,我也参考了这个 "Expected BEGIN_OBJECT but was STRING at line 1 column 1" 并检查了 json 是否有效并在 android studio 中尝试了清理和重建选项

关于java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 13571 列处为 BEGIN retrofit_ARRAY的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Andorid Studio java.lang.IllegalStateException:预期为 BEGIN_ARRAY,但在第 1 行第 2 列路径 $ 处为 BEGIN_OBJECT、Android Java Retrofit 中的错误:预期的 begin_object 但在第 1 行第 5 列路径 $、Android:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法“ java.lang.String java.lang.Object.toString()”、API.java.lang.IllegalStateException:应为 BEGIN_OBJECT,但在第 1 行第 56 列处为 STRING等相关知识的信息别忘了在本站进行查找喔。

本文标签: