spring boot:将打印控制台更改为json rest

时间:2017-08-08 17:41:15

标签: json spring rest spring-boot spring-data

实际上,我在Spring中的项目通过控制台从数据库发送值,如下所示: Console image,但我希望像其他API一样通过JSON发送这些值,但我不知道如何更改它。

{ 
"depositarios": {
"correo": "correo",
"nombre": "nombre",
"numTel": "numTel",
"pApellido": "pApellido",
"SApellido": "sAellido"
}
}

这是我的主要课程:

@SpringBootApplication

@ComponentScan("com.abner.springpostgresql.service.impl, com.abner.springpostgresql.dao.imp")
public class SpringPostgresqlApplication {

    public static void main(String[] args) {
        ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
        depoService depoService =context.getBean(depoService.class);
        depoService.loadAllDepo();
    }
}

这是我已退休的项目来源https://github.com/abnercoronado/restpostgresql

2 个答案:

答案 0 :(得分:0)

您必须使用@RestController注释创建一个RestController,如下所示:

@RestController
public class MyRestController {

    @RequestMapping(value = "/personas", method = RequestMethod.GET)
    public List<Persona> listaPersonas() {

        // This is just a sample. Here you could bring your data form your db
        List<Persona> lista = new ArrayList<Persona>();

        Persona p = new Persona();
        p.setNombre("angel");
        p.setEdad(20);
        lista.add(p);

        return lista;
    }
}

@RequestMapping注释的值(本例中为“/ personas”)将是端点。因此,当您访问端点http://localhost:8080/personas时(假设您的应用正在http://localhost:8080上运行),那么您将获得数据为json。

Here是如何做到这一点的一个例子。

Here是另一个可以帮助你的例子(enespañol)。

答案 1 :(得分:0)

您可以使用ObjectMapper将您的pojo或对象转换为JSON字符串,并使用其他API或任何内容发送到您想要的位置。

或者你可以创建Rest方法和访问API将返回Json值。

@RestController
public class MyRestController {


@RequestMapping(value = "/depo", method = RequestMethod.GET)
public List<?> getDepo() {

  ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
    depoService depoService =context.getBean(depoService.class);
    List<?> lista = depoService.loadAllDepo();
    return lista;
}

另一种做法。

@RestController
public class MyRestController {


@RequestMapping(value = "/depo", method = RequestMethod.GET)
public List<Depo> getDepo() {

  ApplicationContext context= SpringApplication.run(SpringPostgresqlApplication.class, args);
    depoService depoService =context.getBean(depoService.class);
    List<Depo> lista = depoService.loadAllDepo();
    return lista;
}

启动服务器后,可以通过localhost:8080 / depo运行此服务器。你也可以返回XML。