com.google.gson.jsonsyntaxexception:java.lang.illegalstateexception:预期begin_object,但在第2行2列2路径$时是字符串
您好,我正在创建一个Android应用程序,供学生轻松找到住宿的房间,作为学校项目,并且在更新方面遇到了一些麻烦。我使用000webhost.com创建了一个Web服务。我已经知道PUT和DELETE是付款的,但是我的老师告诉我们,我们可以将其嵌入到帖子中并使其正常工作。
这样,我已经可以将删除工作进行工作。但是,我在更新方面遇到了麻烦。当我尝试更新时,所有数据都会更改为我要更改它的内容,但同时又调用了我的Failure方法,它给了我这个错误:com.google.gson.jsonsyntaxexception: begin_object,但在第2行2列路径上是字符串$
iam觉得很奇怪,因为在我的Activiy中,我使用的代码与我的帖子相似(该帖子非常有效),尽管错误,但我的数据已更新,但是我想摆脱错误,因为它不允许我按预期更改活动。
这是我的Web服务,将嵌入在帖子中的嵌入式(使用Slim 4,notorm for web服务)
//Put anuncios
$app->post('/api/editar_anuncios/{id}', function( $request, $response){
require_once('db/dbconnection.php');
$id = $request->getAttribute('id');
$users_id = $request->getParsedBody()["users_id"];
$morada = $request->getParsedBody()["morada"];
$n_quartos = $request->getParsedBody()["n_quartos"];
$latitude = $request->getParsedBody()["latitude"];
$longitude = $request->getParsedBody()["longitude"];
$fotografia = $request->getParsedBody()["fotografia"];
$preco = $request->getParsedBody()["preco"];
$ncasas_banho = $request->getParsedBody()["ncasas_banho"];
$telemovel = $request->getParsedBody()["telemovel"];
$mobilado= $request->getParsedBody()["mobilado"];
$outros_atributos = $request->getParsedBody()["outros_atributos"];
$qrcode = $request->getParsedBody()["qrcode"];
$data = array(
"users_id"=> $users_id,
"morada" => $morada,
"n_quartos" => $n_quartos,
"latitude" => $latitude,
"longitude" => $longitude,
"fotografia"=> $fotografia,
"preco" => $preco,
"ncasas_banho" => $ncasas_banho,
"telemovel" => $telemovel,
"mobilado" => $mobilado,
"outros_atributos" => $outros_atributos,
"qrcode" => $qrcode
);
if(isset($db->anuncios[$id])){
$result = $db->anuncios[$id]->update($data);
if($result){
echo json_encode('O anuncio foi atualizado com sucesso', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('A atualização falhou', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('O anuncio não existe', JSON_UNESCAPED_UNICODE);
return $response;
});
我的端点
@FormUrlEncoded
@POST("editar_anuncios/{id}")
fun editar(@Path("id") id: Int?,
@Field("users_id") users_id: Int?,
@Field("morada") morada: String?,
@Field("n_quartos") n_quartos: Int?,
@Field("latitude") latitude: Double?,
@Field("longitude") longitude: Double?,
@Field("fotografia") fotografia: String?,
@Field("preco") preco: Double?,
@Field("ncasas_banho") ncasas_banho: Int?,
@Field("telemovel") telemovel: String?,
@Field("mobilado") mobilado: String?,
@Field("outros_atributos") outros_atributos: String?,
@Field("qrcode") qrcode: String?): Call<OutputEditar>
我的ServiceBuilder
object ServiceBuilder {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("https://tneveda.000webhostapp.com/RoomForStudents/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T {
return retrofit.create(service)
}
}
我的OutputeDitar
data class OutputEditar(
val users_id: Int,
val morada: String,
val n_quartos: Int,
val latitude: Double,
val longitude: Double,
val fotografia: String,
val preco: Double,
val ncasas_banho: Int,
val telemovel: String,
val mobilado: String,
val outros_atributos: String,
val qrcode: String,
val status: String,
val MSG: String
)
是我的活动中最重要的代码以进行更新。在弹药上,我致电WebService将预期的数据放在我的视图上,并且可以很好地工作。只需放在这里,以显示如何将变量用于我的更新方法的方法
private lateinit var editMoradaView: EditText
private lateinit var editNQuartosView: EditText
private lateinit var shared_preferences: SharedPreferences
private lateinit var latitude : EditText
private lateinit var longitude : EditText
private lateinit var imageView: ImageView
private lateinit var button: Button
private val pickImage = 100
private var imageUri: Uri? = null
private var base64:String? =null
private var fotografia:String? =null
private lateinit var decodedByte: Bitmap
private var isBitMap:Boolean= false
private var ID:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editar_menu)
imageView = findViewById(R.id.preview)
button = findViewById(R.id.upload)
editMoradaView = findViewById(R.id.morada)
editNQuartosView = findViewById(R.id.nquartos)
latitude = findViewById(R.id.latitude)
longitude = findViewById(R.id.longitude)
button.setOnClickListener {
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
startActivityForResult(gallery, pickImage)
}
shared_preferences = getSharedPreferences("shared_preferences", Context.MODE_PRIVATE)
val isLogin = shared_preferences.getBoolean("login",false )
setTitle(R.string.edit)
var id = intent.getStringExtra(DetalhesActivity.PARAM_ID)
val request = ServiceBuilder.buildService(EndPoints::class.java)
val call : Call<List<Anuncio>> = request.getAnunciosById2(id)
call.enqueue(object : Callback<List<Anuncio>> {
override fun onResponse(call: Call<List<Anuncio>>, response: Response<List<Anuncio>>) {
if (response.isSuccessful) {
anuncios = response.body()!!
for (anuncio in anuncios) {
editMoradaView.setText(anuncio.morada)
editNQuartosView.setText(anuncio.n_quartos.toString())
latitude.setText(anuncio.latitude.toString())
longitude.setText(anuncio.longitude.toString())
ID = anuncio.id
val decodedString: ByteArray = Base64.decode(anuncio.fotografia, Base64.DEFAULT)
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
imageView.setImageBitmap(decodedByte)
isBitMap= true
}
}
}
override fun onFailure(call: Call<List<Anuncio>>, t: Throwable) {
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_LONG).show()
}
})
}
,以便检查文件是否是位图,因为当我从手机中选择图片时,我会将其更改为位图和然后转到base64字符串,在该字符串中,我将其插入数据库。但是,当我从数据库中获取图片以将其显示在我的ImageView上时,我将其从base64更改为仅位图并在屏幕上以该格式显示。因此,我必须检查我的文件是哪种格式,要正确更新它(如我所预期的,它可以按照我的意图进行更新,如果我尝试更改图片)。我尝试更改默认值以测试所有内容是否更新,并且所有内容都应尽其所能。但是,它仍然通过onfailure方法传递了错误,我不明白为什么会发生这种错误,以及使错误消失的能力。谢谢
fun editar(view: View) {
val request = ServiceBuilder.buildService(EndPoints::class.java)
val latitude = latitude.text.toString().toDouble()
val longitude = longitude.text.toString().toDouble()
val morada= editMoradaView.text.toString()
val n_quartos = editNQuartosView.text.toString().toInt()
val utilizador_id = shared_preferences.getInt("id", 0)
if(isBitMap){
val base = getBase64String(decodedByte)
fotografia = base
}
else{
fotografia = base64
}
val call = request.editar(
id = ID,
users_id = utilizador_id,
morada = morada,
n_quartos = n_quartos,
latitude = latitude.toString().toDouble(),
longitude = longitude.toString().toDouble(),
fotografia = fotografia,
preco = 21.0,
ncasas_banho = 4,
telemovel= "teste3",
mobilado = "teste3",
outros_atributos = "2",
qrcode = "teste3")
call.enqueue(object : Callback<OutputEditar> {
override fun onResponse(call: Call<OutputEditar>, response: Response<OutputEditar>){
if (response.isSuccessful){
val c: OutputEditar = response.body()!!
Toast.makeText(this@EditarAnuncio, c.MSG, Toast.LENGTH_LONG).show()
val intent = Intent(this@EditarAnuncio, MapsActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onFailure(call: Call<OutputEditar>, t: Throwable){
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
编辑:
我尝试通过将JSON放置在Postman中测试我的更新,并在Postman中起作用。但是,在我的应用程序中,它仍然无法正常工作。而且我不知道自己在应用程序中没有以这种格式(似乎是这种方式),
但是当我尝试将数据插入数据库(与更新相似的代码)时,它可以正常工作而没有任何错误。在我的更新中,它有效,但不能100%,因为它仍然给我这个错误
{
"users_id": 1,
"n_quartos": 2,
"latitude": 20.0,
"longitude": 2.0,
"morada": "teste",
"fotografia": "teste",
"preco": 240,
"ncasas_banho": 4,
"telemovel": 9242424242,
"mobilado": "teste",
"outros_atributos": "teste",
"qrcode": "teste"
}
Hello i am creating an android App for Students to easily find rooms to stay, as a School Project, and i am having some trouble with Update. I created an webservice with 000webhost.com. I already Know put and Delete are paid, but my teacher told us we can embedded it in a POST and make it work.
In that way i was already able to put my DELETE to work. However i am having trouble with the UPDATE. when i try to update, all the data change to what i want to change it, however at the same time my OnFailure method is called and it gives me this error : com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 2 column 2 path $
Iam find it strange, because in my activiy i am using similar code to my POST (that works perfectly) and despite the error, my data is updated, however i want to get rid of the error , since it doesn't allow me to change activity as intended.
Here is my webService PUT embedded in a POST (used slim 4 and NOTORM for the webservice)
//Put anuncios
$app->post('/api/editar_anuncios/{id}', function( $request, $response){
require_once('db/dbconnection.php');
$id = $request->getAttribute('id');
$users_id = $request->getParsedBody()["users_id"];
$morada = $request->getParsedBody()["morada"];
$n_quartos = $request->getParsedBody()["n_quartos"];
$latitude = $request->getParsedBody()["latitude"];
$longitude = $request->getParsedBody()["longitude"];
$fotografia = $request->getParsedBody()["fotografia"];
$preco = $request->getParsedBody()["preco"];
$ncasas_banho = $request->getParsedBody()["ncasas_banho"];
$telemovel = $request->getParsedBody()["telemovel"];
$mobilado= $request->getParsedBody()["mobilado"];
$outros_atributos = $request->getParsedBody()["outros_atributos"];
$qrcode = $request->getParsedBody()["qrcode"];
$data = array(
"users_id"=> $users_id,
"morada" => $morada,
"n_quartos" => $n_quartos,
"latitude" => $latitude,
"longitude" => $longitude,
"fotografia"=> $fotografia,
"preco" => $preco,
"ncasas_banho" => $ncasas_banho,
"telemovel" => $telemovel,
"mobilado" => $mobilado,
"outros_atributos" => $outros_atributos,
"qrcode" => $qrcode
);
if(isset($db->anuncios[$id])){
$result = $db->anuncios[$id]->update($data);
if($result){
echo json_encode('O anuncio foi atualizado com sucesso', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('A atualização falhou', JSON_UNESCAPED_UNICODE);
return $response;
} else
echo json_encode('O anuncio não existe', JSON_UNESCAPED_UNICODE);
return $response;
});
my Endpoints
@FormUrlEncoded
@POST("editar_anuncios/{id}")
fun editar(@Path("id") id: Int?,
@Field("users_id") users_id: Int?,
@Field("morada") morada: String?,
@Field("n_quartos") n_quartos: Int?,
@Field("latitude") latitude: Double?,
@Field("longitude") longitude: Double?,
@Field("fotografia") fotografia: String?,
@Field("preco") preco: Double?,
@Field("ncasas_banho") ncasas_banho: Int?,
@Field("telemovel") telemovel: String?,
@Field("mobilado") mobilado: String?,
@Field("outros_atributos") outros_atributos: String?,
@Field("qrcode") qrcode: String?): Call<OutputEditar>
My ServiceBuilder
object ServiceBuilder {
private val client = OkHttpClient.Builder().build()
private val retrofit = Retrofit.Builder()
.baseUrl("https://tneveda.000webhostapp.com/RoomForStudents/api/")
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun<T> buildService(service: Class<T>): T {
return retrofit.create(service)
}
}
My OutputEditar
data class OutputEditar(
val users_id: Int,
val morada: String,
val n_quartos: Int,
val latitude: Double,
val longitude: Double,
val fotografia: String,
val preco: Double,
val ncasas_banho: Int,
val telemovel: String,
val mobilado: String,
val outros_atributos: String,
val qrcode: String,
val status: String,
val MSG: String
)
The most important code of my Activity for Update. On the OnCreate i call the webservice to put the intended data on my views, and it work perfectly. Just put in here, to show how i get the variables to use on the method for my update
private lateinit var editMoradaView: EditText
private lateinit var editNQuartosView: EditText
private lateinit var shared_preferences: SharedPreferences
private lateinit var latitude : EditText
private lateinit var longitude : EditText
private lateinit var imageView: ImageView
private lateinit var button: Button
private val pickImage = 100
private var imageUri: Uri? = null
private var base64:String? =null
private var fotografia:String? =null
private lateinit var decodedByte: Bitmap
private var isBitMap:Boolean= false
private var ID:Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_editar_menu)
imageView = findViewById(R.id.preview)
button = findViewById(R.id.upload)
editMoradaView = findViewById(R.id.morada)
editNQuartosView = findViewById(R.id.nquartos)
latitude = findViewById(R.id.latitude)
longitude = findViewById(R.id.longitude)
button.setOnClickListener {
val gallery = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI)
startActivityForResult(gallery, pickImage)
}
shared_preferences = getSharedPreferences("shared_preferences", Context.MODE_PRIVATE)
val isLogin = shared_preferences.getBoolean("login",false )
setTitle(R.string.edit)
var id = intent.getStringExtra(DetalhesActivity.PARAM_ID)
val request = ServiceBuilder.buildService(EndPoints::class.java)
val call : Call<List<Anuncio>> = request.getAnunciosById2(id)
call.enqueue(object : Callback<List<Anuncio>> {
override fun onResponse(call: Call<List<Anuncio>>, response: Response<List<Anuncio>>) {
if (response.isSuccessful) {
anuncios = response.body()!!
for (anuncio in anuncios) {
editMoradaView.setText(anuncio.morada)
editNQuartosView.setText(anuncio.n_quartos.toString())
latitude.setText(anuncio.latitude.toString())
longitude.setText(anuncio.longitude.toString())
ID = anuncio.id
val decodedString: ByteArray = Base64.decode(anuncio.fotografia, Base64.DEFAULT)
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
imageView.setImageBitmap(decodedByte)
isBitMap= true
}
}
}
override fun onFailure(call: Call<List<Anuncio>>, t: Throwable) {
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_LONG).show()
}
})
}
My Update method where i check if the file is a Bitmap or not, because when i choose a picture from my phone i change it to Bitmap and then to base64 string, where i insert it this way on my database . But when i get the picture from the database to show it on my ImageView, i change it from base64 to only bitmap and show it in that format on the screen . So i have to check which one of the format my file is, to update it properly (it is working as i intended , as the picture updates if i try to change it). I tried changing the default values to test if everything updates, and everything updates as it should. However it still passes the error from the onFailure method and i don't understand why it is happening, and what i can do to make the error go away. Thank You
fun editar(view: View) {
val request = ServiceBuilder.buildService(EndPoints::class.java)
val latitude = latitude.text.toString().toDouble()
val longitude = longitude.text.toString().toDouble()
val morada= editMoradaView.text.toString()
val n_quartos = editNQuartosView.text.toString().toInt()
val utilizador_id = shared_preferences.getInt("id", 0)
if(isBitMap){
val base = getBase64String(decodedByte)
fotografia = base
}
else{
fotografia = base64
}
val call = request.editar(
id = ID,
users_id = utilizador_id,
morada = morada,
n_quartos = n_quartos,
latitude = latitude.toString().toDouble(),
longitude = longitude.toString().toDouble(),
fotografia = fotografia,
preco = 21.0,
ncasas_banho = 4,
telemovel= "teste3",
mobilado = "teste3",
outros_atributos = "2",
qrcode = "teste3")
call.enqueue(object : Callback<OutputEditar> {
override fun onResponse(call: Call<OutputEditar>, response: Response<OutputEditar>){
if (response.isSuccessful){
val c: OutputEditar = response.body()!!
Toast.makeText(this@EditarAnuncio, c.MSG, Toast.LENGTH_LONG).show()
val intent = Intent(this@EditarAnuncio, MapsActivity::class.java)
startActivity(intent)
finish()
}
}
override fun onFailure(call: Call<OutputEditar>, t: Throwable){
Toast.makeText(this@EditarAnuncio,"${t.message}", Toast.LENGTH_SHORT).show()
}
})
}
Edit:
I tried testing my update in Postman by puting the Json like this, and it worked in Postman. However in my App it is still not working. and i don't understand i am in my app is not getting in this format (it seems this way)
But when i try to insert data in my data base (with my code similar with the update) it works without any error. In my Update it works but not 100% , as it still gives me that error
{
"users_id": 1,
"n_quartos": 2,
"latitude": 20.0,
"longitude": 2.0,
"morada": "teste",
"fotografia": "teste",
"preco": 240,
"ncasas_banho": 4,
"telemovel": 9242424242,
"mobilado": "teste",
"outros_atributos": "teste",
"qrcode": "teste"
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最终解决了我的问题,这个问题有点缺乏我的关注。由于我的数据已得到更新,这意味着我已经从Web服务中获得了回复,但是在某个时候,这引起了该错误,所以我猜想我在应用程序上的代码也许都是正确的,并且问题是在WebService内部,并且bingo bingo
自我正在将变量味精和状态放置在输出介绍中,希望在我的网络服务上找到它们。我在所有帖子和删除上都定义了它们,但是我忘了在我的看台上添加它们,因此我将它们像这样在终点的末端添加,现在它按照我想要的是正常工作。
Finally solved my Issue, and the problem was kinda some lack of attention of my part. Since my data was getting updated that mean that i was gettng a response from my webservice, however at some point it caused that error, so i guessed maybe my code on the app was all correct and the problem was inside the webservice, and Bingo
Since i was putting in my OutputEditar the variables MSG and status, it was expecting to find them on my webservice. I have them defined in all my posts and on my delete, but i forgot to add them on my put so i add them like this on the ending of my endpoint, and now it is working properly as i wanted it.