好吧,每当我尝试在我的Android应用中使用Volley的JSONObjectRequest格式接收由REST Web服务发送的布尔值时,都会出现Validation:com.android.volley.ParseError: org.json.JSONException:value false of type java.jang.Boolean cannot be converted to JSONObject
错误。
我知道使用StringRequest是解决此问题的简便方法,但我真的很想知道是否还有另一种解决方法。
我的猜测是原始的布尔值是问题,因为它不等同于json对象。因此可以通过onResponse(JSONObject response)
齐射方法来抛出例外。
这是Java REST Web服务:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Boolean validate(CreditCard card) {
//instructions
if(/* some conditions */) {
cardList.put(card.getId(), card);
return true;
}
return false;
}
和android应用代码:
public class MainActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_id = findViewById(R.id.id);
et_num = findViewById(R.id.number);
et_type = findViewById(R.id.type);
et_ctrlnb = findViewById(R.id.ctrlnum);
et_expd = findViewById(R.id.expdate);
b_validate = findViewById(R.id.validate);
b_validate.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v == b_validate) {
String request_url = "http://192.168.191.1:8080/RESTCardValidator/rest/cardvalidator";
JSONObject cardDetails = new JSONObject();
try {
cardDetails.put("controlNumber", Integer.parseInt(et_ctrlnb.getText().toString()));
cardDetails.put("expiryDate", et_expd.getText().toString());
cardDetails.put("id", Long.parseLong(et_id.getText().toString()));
cardDetails.put("number", et_num.getText().toString());
cardDetails.put("type", et_type.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, request_url, cardDetails,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Toast.makeText(MainActivity.this, "Validation:" + response.toString(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Validation:" + error.toString(), Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(request);
}
}
如您在图像中所见,接收到值true / false
第一个屏幕截图-
第二个屏幕截图-