0

I am writing an application using Spring and Rstful webservices.

I want the JSOn in the format

{companies : [{name:"companyName", industry : "companyIndustry"} ,
 {name:"companyName", industry : "companyIndustry"}, ]}

But when i fire the url am getting JSON in a different format

{
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"
}-
-
}

My Code

@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;

}



}

where Company object has two String fields for companyName and industry.

How can I modify it to get the JSON in desired format ?

r5d
  • 579
  • 5
  • 24
Abhi
  • 6,471
  • 6
  • 40
  • 57

2 Answers2

0

To return the JSON in formatted way you have to create a view accordingly (Lets say JsonView) if you have not created any one. In your XML you can define it

<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>
0

Actaully it was my mistake , the code is working fine . as i am using Advanced Rest Client for Chrome, it formatted my JSON result . If you call the url on a browser, it works fine as mentioned.

[{"companyName":"Uber","industry":"Transportation"},{"companyName":"CVS","industry":"Pharmacy"},{"companyName":"Orange","industry":"Telecom"},{"companyName":"BostonDynamics","industry":"Robotics"},{"companyName":"Tesla","industry":"Transportation"},{"companyName":"Areva","industry":"Energy"}]
Abhi
  • 6,471
  • 6
  • 40
  • 57