2017-04-03 74 views
0

我正试图读取服务上的客户端发送的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; 
      } 
    } 

我送邮递员从请求。 Postman setup

+0

你有没有在身体的要求是什么? – Diabolus

+0

{ “first_name”:“datta”, “last_name”:“vamshi” } –

+0

@mismanc你能否给我提供一个例子。 –

回答

1

使用@RequestBody注释来读取请求头发布的数据

public JSONObject Signmeup(@RequestBody String inputJsonObj) throws { 
//your code 
    } 
+0

我找不到“@RequestBody”标签。 –

+0

尝试导入此** org.springframework.web.bind.annotation.RequestBody **包。 –

0

如果您希望从服务上的客户端发送的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; 
    } 
} 
+0

SEVERE:RuntimeException无法映射到响应,重新抛出HTTP容器 org.json.JSONException:找不到JSONObject [“first_name”]。 –

+0

@TumuluriVDattaVamshi在'inputJsonObj'的'Signmeup'方法内部执行'sysout'并显示你在'sysout'里面得到了什么?像'System.out.println(“inputJsonObj:”+ inputJsonObj);' – user3441151

+0

@TumuluriVDattaVamshi我只是更新我的答案。你可以试试这个。 – user3441151