我只是想在nodeJS中对我的API的请求体中创建一个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();
修改
问题是我没有正确创建我的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();
答案 0 :(得分:1)
“{patientAddress:”
这不是有效的JSON。
您需要引用密钥。
"{\"patientAddress\" :\"" + patientAddress + "\"}"
但是,请使用适当的JSON库来构建JSON对象字符串
JSONObject params = new JSONObject();
params.put("patientAddress", patientAddress);
请求params.toString()
您还可以使用Okhttp上的Retrofit从您的API中创建Java对象