如何在eclipse中使用spring rest api将数据转换为json格式

时间:2016-12-28 06:19:22

标签: java spring rest

我是初学者api所以我需要通过使用spring rest api将数据转换为json格式。任何人都可以告诉我如何做到这一点并给我原型如何继续这个...

6 个答案:

答案 0 :(得分:1)

您可以使用@RestController或@ReponseBody注释 官方教程是here。代码片段就像

@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));
    }
}
当所有控制器处理程序都应该返回一个JSON字符串时,可以使用@RestController注释。但是如果你需要的是某些方法可能返回JSON字符串,只需在该方法上面使用@ResponseBody。并返回一个Object.Spring框架将为你做序列化工作。代码片段如下:

<?php
$url = $_SERVER["HTTP_X_REQUESTED_WITH"];
$url1 = "com.chatadda.free";
$url2 = "com.chatadda.android";
$url3 = "com.chatadda.android.pro";
$url4 = "com.chatadda.android.premium";
if($url != $url1 || $url != $url2 || $url != $url3 || $url != $url4) {
echo "Not on App";
echo $_SERVER["HTTP_X_REQUESTED_WITH"];
}
else {
echo "On App";
}
?>

答案 1 :(得分:0)

对正在返回数据的方法使用@ResponseBody注释...此外,如果您可以显示代码,则会更有帮助

答案 2 :(得分:0)

你可以使用jackson库

Jackson library

答案 3 :(得分:0)

Spring引导使用Jackson将JSON反序列化为Java实例,并将Java对象序列化为JSON有效负载。你可以在这里查看我写的示例项目[1]。从字面上看,您不需要操纵任何JSON。您使用Java对象。让Jackson负责Java对象和JSON有效负载之间的转换。你只需要遵循一些规则。例如,您的Java类应具有与JSON有效负载和兼容数据类型相同的字段名称,然后Jackson将代表您绑定它们。希望这可以帮助。快乐的编码。

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

答案 4 :(得分:0)

除了CALTyang的答案,我们还可以使用ResponseEntity来返回响应。

代码段:

        @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 :(得分:0)

@ user7271107 - 这是示例原型代码和响应格式。我从数据库中获取数据。

Records

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

响应

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