[英]Sending JSON Post Request to Rest Web Service in Java
I am trying to send a value to my dummy Rest Web Service inside a JSON string. 我试图将值发送到JSON字符串内的虚拟Rest Web Service。 However, the service couldn't get the value that I sent. 但是,该服务无法获取我发送的值。
Firstly, my JAX-RS code is like that: 首先,我的JAX-RS代码是这样的:
@POST
@Path("/ser1")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response convertFtoCfromInput(final BasicModel bm) throws JSONException {
System.out.println("Value is " + bm.value);
JSONObject jsonObject = new JSONObject();
float celsius;
celsius = (bm.value - 32) * 5 / 9;
jsonObject.put("F Value", bm.value);
jsonObject.put("C Value", celsius);
String result = "@Produces(\"application/json\") Output: \n\nF to C Converter Output: \n\n" + jsonObject;
return Response.status(200).entity(result).build();
}
where the BasicModel class is: BasicModel类为:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class BasicModel {
@XmlElement float value;
}
I am sending a POST request to the ".../ftocservice/ser1" using Postman and body of my request is: 我正在使用邮递员向“ ... / ftocservice / ser1”发送POST请求,我的请求正文为:
{"value": 900.0}
When I send the request, the service couldn't get the value 900.0. 当我发送请求时,服务无法获取值900.0。 It prints "Value is 0.0" and returns: {"C Value": -17.77777862548828, "F Value": 0} 它显示“值是0.0”并返回:{“ C值”:-17.77777862548828,“ F值”:0}
Where did I do wrong? 我在哪里做错了? Thanks already for your help. 感谢您的帮助。
Resources: 资源:
I solved the issue! 我解决了这个问题!
I removed the "XmlElement" tag from the value and made it private. 我从值中删除了“ XmlElement”标签,并将其设为私有。 I created getter and setter for it and it worked. 我为此创建了getter和setter,并且有效。
So, the final code of BasicModel is: 因此,BasicModel的最终代码是:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class BasicModel {
private float value;
public float getValue(){
return value;
}
public float setValue(float value){
this.value = value;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.