How do I convert an existing XML-based web service to JSON-type web service?
如何将现有的基于XML的Web服务转换为JSON类型的Web服务?
I have this sample resource:
我有这个示例资源:
@Controller
public class CustomerController {
@RequestMapping(value="customers", method=RequestMethod.GET)
public @ResponseBody CustomerList customers(Model model) {
CustomerList list = new CustomerList();
list.getCustomer().add(new Customer("1", "John Doe"));
list.getCustomer().add(new Customer("2", "Jane Doe"));
return list;
}
}
So far, I am not experiencing any error with regards to accessing it, I just want to change the data that this service return to the client from XML to JSON.
到目前为止,我没有遇到任何关于访问它的错误,我只想将此服务返回到客户端的数据从XML更改为JSON。
With this entity:
有了这个实体:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"customer"
})
@XmlRootElement(name = "CustomerList")
public class CustomerList {
@XmlElement(name = "Customer", required = true)
protected List<Customer> customer;
public List<Customer> getCustomer() {
if (customer == null) {
customer = new ArrayList<Customer>();
}
return this.customer;
}
}
servlet-context.xml:
<oxm:jaxb2-marshaller id="marshaller" contextPath="com.mycompany.api.model"/>
<beans:bean id="customerList" class="org.springframework.web.servlet.view.xml.MarshallingView">
<beans:constructor-arg ref="marshaller"/>
</beans:bean>
How can I change the output of the service to JSON? Do I need to put JSON-type annotations in the entity/model?
如何将服务的输出更改为JSON?我是否需要在实体/模型中添加JSON类型的注释?
1 个解决方案
#1
0
Using Jackson JSON processor, your code would remarkably similar. The model will be in simple POJO format. Use @ResponseBody for your response again and Jackson will take care of the JSON conversion.
使用Jackson JSON处理器,您的代码非常相似。该模型将采用简单的POJO格式。再次使用@ResponseBody进行回复,Jackson将负责JSON转换。
See this Spring 3 MVC and JSON example.
请参阅Spring 3 MVC和JSON示例。
#1
0
Using Jackson JSON processor, your code would remarkably similar. The model will be in simple POJO format. Use @ResponseBody for your response again and Jackson will take care of the JSON conversion.
使用Jackson JSON处理器,您的代码非常相似。该模型将采用简单的POJO格式。再次使用@ResponseBody进行回复,Jackson将负责JSON转换。
See this Spring 3 MVC and JSON example.
请参阅Spring 3 MVC和JSON示例。