Reputation: 11
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...
Upvotes: 0
Views: 3041
Reputation: 1341
@user7271107 - here is sample prototype code and response format.I am fetching the data from DB.
=====================================================
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();
}
Upvotes: 0
Reputation: 1341
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);
}
}
Upvotes: 0
Reputation: 1258
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));
}
}
Upvotes: 1
Reputation: 21124
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/
Upvotes: 0
Reputation: 51
Use @ResponseBody
annotation on your method which is returning data...Also if you can show the code it will be more helpful
Upvotes: 0