OkHttp Android发布原因错误JSON格式错误
我只是试图在nodeJS中的API的请求正文中创build一个JSON对象。 我不断收到我的服务器端的这个错误:
SyntaxError: Unexpected token p in JSON at position 1
这里是我如何使用OkHttpClient制作我的请求:
String patientAddress = "0x83d0aa553df8bbf2c70c8250a1edbdef5be2ccbe"; MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "{patientAddress:" + patientAddress + "}"); Request request = new Request.Builder() .url(getString(R.string.main_url) + "/api/getPatientDetails") .headers(buildStandardHeaders(Stormpath.accessToken())) .post(body) .build();
编辑
问题是,我没有创build我的JSON的权利,这里是工作代码:
String patientAddress = "0x83d0aa553df8bbf2c70c8250a1edbdef5be2ccbe"; MediaType JSON = MediaType.parse("application/json; charset=utf-8"); RequestBody body = RequestBody.create(JSON, "{\"patientAddress\" :\"" + patientAddress + "\"}"); Request request = new Request.Builder() .url(getString(R.string.main_url) + "/api/getPatientDetails") .headers(buildStandardHeaders(Stormpath.accessToken())) .post(body) .build();
“{patientAddress:”
这不是有效的JSON。
你需要引用密钥。
"{\"patientAddress\" :\"" + patientAddress + "\"}"
但是,请使用适当的JSON库来构buildJSON对象string
JSONObject params = new JSONObject(); params.put("patientAddress", patientAddress);
请求与params.toString()
您也可以使用Okhttp的Retrofit从您的API制作Java对象