我正在尝试开发一个程序,它允许您将JSON对象发送到服务器,然后读取该对象以便将数据存储在数据库中,但我无法实现这一点。这是我的代码,你能告诉我哪里出错了以及我该怎么纠正它?
这是我的APIService
:
@POST("testingjson.php")
Call<Result> confirmOrder(
@Body JSONObject productCart
);
以下是Result
类:
public class Result {
private JSONObject cartProducts;
public JSONObject getCartProducts() {
return cartProducts;
}
public void setCartProducts(JSONObject cartProducts) {
this.cartProducts = cartProducts;
}
}
最后,这是按钮clicklistener
上的服务电话:
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build();
APIService service = retrofit.create(APIService.class);
Call<Result> call=service.confirmOrder(Cart);
call.enqueue(new Callback<Result>() {
@Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(getApplicationContext(),"OrderPlaced",Toast.LENGTH_LONG).show();
}
@Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});
以下是发送它的PHP代码,以便将元素存储到服务器上的数据库中:
<?php
$password="";
$user="root";
$database="shadowpets";
$host="localhost";
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
if($_SERVER["REQUEST_METHOD"]=="POST") {
$jsonData=file_get_contents("php://input");
$jsonString=json_decode($jsonData,true);
try {
foreach($jsonString['Order Summary'] as $cart) {
$name=$cart['ProductName'];
$price=$cart['ProductPrice'];
$quantity=$cart['ProductQuantity'];
$cost=$cart['ProductCost'];
$seller=$cart['SellerId'];
$stmt=$con->prepare("INSERT INTO sProducts(Name,Price,Quantity,Cost,Sellerid)VALUES(?,?,?,?,?)");
$stmt->bind_param("sssss",$name,$price,$quantity,$cost,$seller);
$stmt->execute();
}
$res['result']="data inserted";
} catch(Exception $ex) {
$res['result']=$ex;
}
print_r (json_encode($res));
}
?>
运行应用程序后,我收到以下错误:
com.google.gson.JsonSyntaxException:java.lang.illlegalStateException:预期为BEGIN_OBJECT,但在第1行第1列路径为$
有人能告诉我哪里出错了,以及如何纠正这个错误?