当发布数据显示此错误Android改造预期BEGIN_OBJECT但是是STRING

时间:2018-06-18 13:02:10

标签: android laravel api postdata

Hello开发人员我正在开发一个使用android和php(laravel)的网络基础聊天系统,所以在我的情况下我使用laravel.my实现一个Rest API发送聊天消息问题是当我将数据发布到服务器时(发送消息)没有任何案例消息保存在数据库中。我的Android客户端响应总是转到" onFailure"并显示此错误

  

预计BEGIN_OBJECT但在STRING第1行第1道路$

我尝试了许多方法,遗憾的是我无法找到解决这个问题的正确方法。任何人都可以帮助我,这对我来说是一个有价值的帮助。谢谢你......

这是我的API代码

 public function PostDataToChatRoom(Request $request){

  $ChatRoom=$request->ChatroomId;

  if($ChatRoom == '1'){

  }
  elseif ($ChatRoom == "2"){

      $message= new Message();
      $message->SenderId = $request->input('SenderId');
      $message->ChatroomId = $request ->input('ChatroomId');
      $message->MessageTxt =$request ->input('MessageTxt');
      $message->SenderName=$request->input('SenderName');

      if($message->save())
      {
          event(
              new ForxChatEvent($message)
          );

          return response()->json([$message],200);
      }
  }
  else{
      echo 'aaa';
  }

}

这是我的API响应数据

[
{
    "SenderId": "123",
    "ChatroomId": "2",
    "MessageTxt": "yooo",
    "SenderName": "Test",
    "updated_at": "2018-06-18 12:44:41",
    "created_at": "2018-06-18 12:44:41",
    "id": 189
}
]

这是我的Android代码段...使用改造库将数据发布到服务器

ApiInterface类

public interface PostChatRoomMessage {
@POST("/SendToChatRoom")
Call<Message> PostMessage(@Body Message message);
}

消息类

public class Message implements Serializable {

@SerializedName("messages")
@Expose
private List<Message> messages;

public List<Message> getMessages() {
    return messages;
}

public void setMessages(List<Message> messages) {
    this.messages = messages;
}

@SerializedName("SenderId")
@Expose
private String senderId;
@SerializedName("ChatroomId")
@Expose
private String chatroomId;
@SerializedName("MessageTxt")
@Expose
private String messageTxt;
@SerializedName("SenderName")
@Expose
private String senderName;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("id")
@Expose
private int id;

public String getSenderId() {
    return senderId;
}

public void setSenderId(String senderId) {
    this.senderId = senderId;
}

public String getChatroomId() {
    return chatroomId;
}

public void setChatroomId(String chatroomId) {
    this.chatroomId = chatroomId;
}

public String getMessageTxt() {
    return messageTxt;
}

public void setMessageTxt(String messageTxt) {
    this.messageTxt = messageTxt;
}

public String getSenderName() {
    return senderName;
}

public void setSenderName(String senderName) {
    this.senderName = senderName;
}

public String getUpdatedAt() {
    return updatedAt;
}

public void setUpdatedAt(String updatedAt) {
    this.updatedAt = updatedAt;
}

public String getCreatedAt() {
    return createdAt;
}

public void setCreatedAt(String createdAt) {
    this.createdAt = createdAt;
}

public int getId() {
    return id;
}

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

`

发送消息方法

 public void SendMessage(){

    String SenderId="123";
    String ChatroomId="2";
    String Message=messageEdit.getText().toString();
    String SenderName="yooo";



    if(TextUtils.isEmpty(Message)){
        AlertDialog.Builder builder=new AlertDialog.Builder(Chat.this);
        builder.setMessage("Please add Some Message")
                .setNegativeButton("Ok",null);

        AlertDialog alertDialog=builder.create();
        alertDialog.show();
    }
    else {
        Log.e("not empryy","not empty");

try{
Message message=new Message();
message.setSenderId(SenderId);
message.setChatroomId(ChatroomId);
message.setMessageTxt(Message);
message.setSenderName(SenderName);

OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .addInterceptor(new okhttp3.Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {

                Request request = chain.request().newBuilder()

                        .addHeader("Content-Type", "text/html; charset=UTF-8")
                        .build();

                return chain.proceed(request);

            }
        }).addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        .readTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
        .build();

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setLenient();
Gson gson = gsonBuilder.create();





Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(Config.Api)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

PostChatRoomMessage service=retrofit.create(PostChatRoomMessage.class);
Call<Message> call = service.PostMessage(message);

Log.d("onResponse", "There rtutrutris an error");
call.enqueue(new Callback<Message>() {
    @Override
    public void onResponse(Call<Message> call, Response<Message>response) {
        Log.d("responce sucessregister", response.message());
        messageEdit.setText("");
    }
    @Override
    public void onFailure(Call<Message> call, Throwable t) {
        Log.d("OnbbbbResponse", t.getMessage());
    }    });
}
catch (Exception e){
Log.d("onResponse", "There is an error");
e.printStackTrace();
}        }
}

2 个答案:

答案 0 :(得分:0)

在我看来,你应该确保返回值始终是Json。现在你有时只返回字符串:

echo 'aaa';

这可能是导致此错误的原因。

此外,在某些其他情况下,您不会返回任何可能也有问题的响应,例如:

if($ChatRoom == '1'){

}

这里再没有对象作为回复返回。

答案 1 :(得分:0)

您可以尝试声明Array Object

Enumerable.SequenceEquals

https://drive.google.com/open?id=1_chkVXQHhOsYgbJtWHokBs1Y-cSLtiBb

:)