如何在RESTful服务端请求读取JSON消息。
我正试图读取服务上的客户端发送的JSON数据。 无论我尝试我在控制台中获得一个空对象。 //我的服务如何在RESTful服务端请求读取JSON消息。
@Path("signup")
public class signupservice {
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject Signmeup(JSONObject inputJsonObj) throws JSONException {
String fname = inputJsonObj.toString();
System.out.println(fname);
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", "output");
return outputJsonObj;
}
}
使用@RequestBody注释来读取请求头发布的数据
public JSONObject Signmeup(@RequestBody String inputJsonObj) throws {
//your code
}
我找不到“@RequestBody”标签。 –
尝试导入此** org.springframework.web.bind.annotation.RequestBody **包。 –
如果您希望从服务上的客户端发送的JSON中获取first_name和last_name。你可以试试这个。
@Path("signup")
public class signupservice {
@POST
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject Signmeup(String inputJsonObj) throws JSONException {
JSONObject innerJson = new JSONObject(inputJsonObj);
//Get first_name and last_name from JSON
String fname = innerJson.getString("first_name");
String lname = innerJson.getString("last_name");
System.out.println(fname);
System.out.println(lname);
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", "output");
return outputJsonObj;
}
}
SEVERE:RuntimeException无法映射到响应,重新抛出HTTP容器 org.json.JSONException:找不到JSONObject [“first_name”]。 –
@TumuluriVDattaVamshi在'inputJsonObj'的'Signmeup'方法内部执行'sysout'并显示你在'sysout'里面得到了什么?像'System.out.println(“inputJsonObj:”+ inputJsonObj);' – user3441151
@TumuluriVDattaVamshi我只是更新我的答案。你可以试试这个。 – user3441151
你有没有在身体的要求是什么? – Diabolus
{ “first_name”:“datta”, “last_name”:“vamshi” } –
@mismanc你能否给我提供一个例子。 –