简体   繁体   English

如何在Eclipse中使用Spring Rest API将数据转换为JSON格式

[英]How to convert data into json format by using spring rest api in eclipse

我是spring rest api的新手,所以我需要使用spring rest api将数据转换为json格式,我可以告诉我如何执行此操作,并给我protype如何进行此操作...

You can use @RestController or @ReponseBody annotation. 您可以使用@RestController或@ReponseBody批注。
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: 当所有控制器处理程序都应返回JSON字符串时可以使用@RestController批注。但是,如果您需要某种方法可以返回JSON字符串,只需在该方法上方使用@ResponseBody并返回一个Object。Spring框架将进行序列化为您工作。代码段如下:

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

在返回数据的方法上使用@ResponseBody批注...此外,如果可以显示代码,它将更有帮助

you can use the jackson library 你可以使用杰克逊图书馆

Jackson library 杰克逊图书馆

Spring boot uses Jackson to deserialize JSON into Java instances and serialize Java objects back to JSON payloads. Spring Boot使用Jackson将JSON反序列化为Java实例,并将Java对象序列化回JSON负载。 You may check the sample project written by me here [1]. 您可以在这里查看我编写的示例项目[1]。 Literally you don't need to manipulate any JSON. 从字面上看,您不需要操纵任何JSON。 You work using Java Objects. 您使用Java对象工作。 Let Jackson take care of the transformation between Java Objects and JSON payloads. 让Jackson负责Java对象和JSON有效负载之间的转换。 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. 例如,您的Java类应具有与JSON有效负载相同的字段名称和兼容的数据类型,然后Jackson将代表您绑定它们。 Hope this helps. 希望这可以帮助。 Happy Coding. 编码愉快。

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

In addition to CALTyang answer , we can also use ResponseEntity to return the response. 除了CALTyang答案之外,我们还可以使用ResponseEntity返回响应。

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);
            }

        }

@user7271107 - here is sample prototype code and response format.I am fetching the data from DB. @ user7271107-这是示例原型代码和响应格式。我正在从数据库中获取数据。

记录

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

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();
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM