0

I am new to spring rest api so i need to convert data into json format by using spring rest api can i any one tell me how to do this and give me the protype how to proceed this one...

4
  • fallow this spring.io/guides/gs/rest-service Commented Dec 28, 2016 at 6:25
  • If you use the defaults (particularly with Spring Boot), you don't have to do anything. Just pass or return a POJO, and Spring will do everything for you. Commented Dec 28, 2016 at 6:28
  • @Lovababu,@chrylis thanks for answering.. Commented Dec 28, 2016 at 11:24
  • if mine data is in time and distace values how to code Commented Dec 28, 2016 at 11:26

6 Answers 6

1

You can use @RestController or @ReponseBody annotation.
Official Tutorial is here.And the code snippet is like

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}

@RestController annotation can be used when all the controller handler should return a JSON string.However if your need is that some method may return JSON string,just use @ResponseBody above that method.And return a Object.The Spring framework will do the serialize work for you.The code snippet is like:

@Controller
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    @ResponseBody
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

you can use the jackson library

Jackson library

Comments

0

Use @ResponseBody annotation on your method which is returning data...Also if you can show the code it will be more helpful

Comments

0

Spring boot uses Jackson to deserialize JSON into Java instances and serialize Java objects back to JSON payloads. You may check the sample project written by me here [1]. Literally you don't need to manipulate any JSON. You work using Java Objects. Let Jackson take care of the transformation between Java Objects and JSON payloads. You just need to follow up few rules. For an example your Java class should have same field names as JSON payload and compatible data types, then Jackson will bind them on your behalf. Hope this helps. Happy Coding.

[1] https://github.com/ravindraranwala/SpringBootRxJava/

Comments

0

In addition to CALTyang answer , we can also use ResponseEntity to return the response.

code snippet :

        @RestController
        public class PersonController {

            @Autowired
            private PersonRepository personRepository;

            @RequestMapping(value = "/persons/{id}", method = RequestMethod.GET,produces={MediaType.APPLICATION_XML_VALUE},headers = "Accept=application/xml")
            public ResponseEntity<?> getPersonDetails(@PathVariable Long id, final HttpServletRequest request)throws Exception {
                ConnectionManager cm=new ConnectionManager();
                Person personResponse=cm.getDetails();
                return ResponseEntity.ok(personResponse);
            }

        }

5 Comments

can you tell how to do with my data as time and distace values
@user7271107 - Can you please paste your code regarding data as time and distance value
time in hr ={1,2,3,4,,5,6} distance in km={20,23,29,50,55,60} this is mine sample data of time and distance
Are you getting this data from DB and are you expecting the below json format ? { "hr": [ 1, 2, 3, 4, 5, 6 ], "km": [ 20, 23, 29, 50, 55, 60 ] }
as i am having that data in excel file i want that in json format by using spring rest api
0

@user7271107 - here is sample prototype code and response format.I am fetching the data from DB.

Records

=====================================================

Response

{
    "records":
    [
        {
            "hr": 1,
            "km": 20
        },
        {
            "hr": 2,
            "km": 23
        },
        {
            "hr": 3,
            "km": 29
        },
        {
            "hr": 4,
            "km": 50
        },
        {
            "hr": 5,
            "km": 55
        },
        {
            "hr": 6,
            "km": 60
        }
    ]
}

            package com.subu;

            import org.springframework.boot.SpringApplication;
            import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
            import org.springframework.boot.autoconfigure.SpringBootApplication;
            import org.springframework.boot.builder.SpringApplicationBuilder;
            import org.springframework.boot.context.web.SpringBootServletInitializer;
            import org.springframework.context.annotation.ComponentScan;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.scheduling.annotation.EnableScheduling;


            @SpringBootApplication
            @Configuration
            @ComponentScan
            @EnableAutoConfiguration
            @EnableScheduling
            public class Application extends SpringBootServletInitializer{



               public static void main(String[] args) {
                  SpringApplication.run(Application.class, args);
               }

               @Override
               protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
                   return application.sources(Application.class);
               }

               private static Class<Application> applicationClass = Application.class;

            }

            @RestController
            public class PersonController {

                @Autowired
                private RecordRepository  recordRepository;


                @RequestMapping(value = "/records/", method = RequestMethod.GET,produces={MediaType.APPLICATION_JSON_VALUE},headers = "Accept=application/json")
                public ResponseEntity<?> getRecords(final HttpServletRequest request)throws Exception {
                    DBRecordArray dr= new DBRecordArray();
                    List<DBRecord> list=recordRepository.findAll();
                    dr.setRecords(list);
                    return ResponseEntity.ok(dr);
                }

            }

            package com.subu;

            import java.io.Serializable;

            import javax.persistence.Entity;
            import javax.persistence.GeneratedValue;
            import javax.persistence.Id;
            import javax.persistence.Table;


            @Entity
            @Table(name="record")
            public class DBRecord implements Serializable{

                private static final long serialVersionUID = 1L;
                @Id
                @GeneratedValue
                private Long id;

                private int hr;
                private int km;
                public int getHr() {
                    return hr;
                }
                public void setHr(int hr) {
                    this.hr = hr;
                }
                public int getKm() {
                    return km;
                }
                public void setKm(int km) {
                    this.km = km;
                }

            }

            package com.subu;

            import java.util.List;

            public class DBRecordArray {

                private List<DBRecord> records;

                public List<DBRecord> getRecords() {
                    return records;
                }

                public void setRecords(List<DBRecord> records) {
                    this.records = records;
                }
            }

            package com.subu;


            import java.util.List;

            import org.springframework.data.jpa.repository.JpaRepository;

            public interface RecordRepository extends JpaRepository<DBRecord, Long> {

                List<DBRecord> findAll();
            }

5 Comments

ur fetching from DB but our data is in excel so how to fetch data from excel can you ple tell me and thanks for coding for the solution..it so usefull for me
can i know ur mail id for the contacting purpose
can you please tell me the program flow
can you please tell me how to fetch data from excel

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.