【发布时间】:2013-09-13 08:34:08
【问题描述】:
如何在 REST Web 服务中发送 JSON 数据? 我有一个 json 对象,其中包含产品 ID、商店 ID、价格、产品单位、数量 values.Here 除产品单位值外,所有值均为整数。 现在,我想将这些值发送到 REST Web 服务中。 您能否提供任何样品或任何有价值的建议?
【问题讨论】:
标签: json web-services rest ibm-mobilefirst
如何在 REST Web 服务中发送 JSON 数据? 我有一个 json 对象,其中包含产品 ID、商店 ID、价格、产品单位、数量 values.Here 除产品单位值外,所有值均为整数。 现在,我想将这些值发送到 REST Web 服务中。 您能否提供任何样品或任何有价值的建议?
【问题讨论】:
标签: json web-services rest ibm-mobilefirst
您的 JSON 输入:
{
"productId": "p123",
"storeId": "s456",
"price": 12.34,
"productUnit": "u789",
"quantity": 42
}
JAXB 类:
@XmlRootElement
public class MyJaxbBean {
public String productId;
public String storeId;
public double price;
public String productUnit;
public int quantity;
public MyJaxbBean() {} // JAXB needs this
public MyJaxbBean(String productId, String storeId, double price, String productUnit, int quantity) {
// set members
}
}
JAX-RS 方法。
@PUT
@Consumes("application/json")
public Response putMyBean(MyJaxbBean theInput) {
// Do something with theInput
return Response.created().build();
}
有关详细信息,请参阅 the documentation of Jersey(JAX-RS 的 RI)。
【讨论】:
@Consumes("application/json") 足以将 JSON 映射到 MyJaxbBean。
由于您已使用 Worklight 标记对此进行了标记,因此我假设您的意思是询问如何将 json 数据从 Worklight 客户端发送到外部 REST 服务。为了在 Worklight 中执行此操作,您需要使用 Worklight HTTP 适配器。请参阅此处的文档:http://public.dhe.ibm.com/software/mobile-solutions/worklight/docs/v600/04_02_HTTP_adapter_-_Communicating_with_HTTP_back-end_systems.pdf
创建 Worklight 适配器后,您可以像这样从客户端发送 JSON 数据:
/**********************************************************************************
* Http Adapter call
**********************************************************************************/
function callAdapter(){
var myJSONObject = {
productId: 123,
storeId: 123,
price: 342,
productUnit: "myUnit",
quantity: 4
};
var invocationData = {
adapter : 'MyHttpAdapter',
procedure : 'myAdapterProcedure',
parameters : [myJSONObject]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : success,
onFailure : failure
});
}
function success(response){
console.log("adapter Success");
console.log(response);
}
function failure(response){
console.log("adapter Failure");
console.log(response);
}
【讨论】: