我正在使用Spring和Rstful webservices编写应用程序。
我想要格式为
的JSOn{companies : [{name:"companyName", industry : "companyIndustry"} ,
{name:"companyName", industry : "companyIndustry"}, ]}
但是当我触发网址时,我会以不同的格式获取JSON
{
companies: [5]
0: {
companyName: "Uber"
industry: "Transportation"
}-
1: {
companyName: "CVS"
industry: "Pharmacy"
}-
2: {
companyName: "Orange"
industry: "Telecom"
}-
3: {
companyName: "BostonDynamics"
industry: "Robotics"
}-
4: {
companyName: "Tesla"
industry: "Transportation"
}-
-
}
我的代码
@RestController
public class CompanyController {
public static final Company companiesArray[] = {
new Company("Uber", "Transportation"),
new Company("CVS", "Pharmacy"), new Company("Orange", "Telecom"),
new Company("BostonDynamics", "Robotics"),
new Company("Tesla", "Transportation") };
@RequestMapping(value = "/companies", method = RequestMethod.GET)
private Map getAllCompanies() {
Map companyMap = new HashMap<String,String>();
companyMap.put("companies", companiesArray);
return companyMap;
}
}
其中Company对象有companyName和industry的两个String字段。
如何修改它以获得所需格式的JSON?
答案 0 :(得分:0)
要以格式化方式返回JSON,您必须相应地创建一个视图(让我们说JsonView),如果你还没有创建任何一个。 在您的XML中,您可以定义它
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" >
<property name="prefixJson" value="false" />
<property name="objectMapper" ref="jacksonObjectMapper" />
<property name="renderedAttributes">
<set>
<value>"Json-Value"</value>
</set>
</property>
</bean>
答案 1 :(得分:0)
实际上这是我的错误,代码工作正常。因为我正在使用Chrome的Advanced Rest Client,它格式化了我的JSON结果。如果您在浏览器上调用网址,则可以正常工作。
[{"companyName":"Uber","industry":"Transportation"},{"companyName":"CVS","industry":"Pharmacy"},{"companyName":"Orange","industry":"Telecom"},{"companyName":"BostonDynamics","industry":"Robotics"},{"companyName":"Tesla","industry":"Transportation"},{"companyName":"Areva","industry":"Energy"}]