首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >REST请求不显示List<object>为JSON

问REST请求不显示List<object>为JSON
EN

Stack Overflow用户
提问于 2019-03-02 11:26:56
回答 2查看 684关注 0票数 2

我是Spingboot的新手,我做了一个非常简单的应用程序的演示(一个示例),将类列表显示为JSON,但我得到了一个错误。我在配置/依赖关系中遗漏了什么?

我的pom.xml:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>2.1.3.RELEASE</version>
          <relativePath/> <!-- lookup parent from repository -->
     </parent>
     <groupId>com.beniregev</groupId>
     <artifactId>booking-demo</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>booking-demo</name>
     <description>Demo project for Spring Boot</description>

     <properties>
          <java.version>1.8</java.version>
     </properties>

     <dependencies>
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
          </dependency>
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-jpa</artifactId>
          </dependency>
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
          </dependency>
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
          </dependency>

          <dependency>
                <groupId>org.hsqldb</groupId>
                <artifactId>hsqldb</artifactId>
                <scope>runtime</scope>
          </dependency>
          <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
          </dependency>
     </dependencies>

     <build>
          <plugins>
                <plugin>
                     <groupId>org.springframework.boot</groupId>
                     <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
          </plugins>
     </build>

 </project>

我的目录结构:

​

DemoController.java -这是有效的("localhost:8080/hello")

代码语言:javascript
复制
package com.beniregev.bookingdemo;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    @RequestMapping("/hello")
    public String hello() {
        return "Hello";
    }
}

HotelBooking.java

代码语言:javascript
复制
package com.beniregev.bookingdemo;

public class HotelBooking {
    private String hotelName;
    private double pricePerNight;
    private int numberOfNights;

    public HotelBooking(String hotelName, double pricePerNight, int numberOfNights) {
        this.hotelName = hotelName;
        this.pricePerNight = pricePerNight;
        this.numberOfNights = numberOfNights;
    }

    public String getHotelName() {
        return hotelName;
    }

    public double getPricePerNight() {
        return pricePerNight;
    }

    public int getNumberOfNights() {
        return numberOfNights;
    }

    public double getTotalPrica() {
        return pricePerNight * numberOfNights;
    }
}

BookingController.java

代码语言:javascript
复制
package com.beniregev.bookingdemo;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value="/bookings")
public class BookingController {
    private List<HotelBooking> bookings;

    public BookingController() {
        bookings = new ArrayList<>();

        bookings.add(new HotelBooking("Marriot", 200.50, 3));
        bookings.add(new HotelBooking("Novotel", 140.74, 1));
        bookings.add(new HotelBooking("Ibis", 90.0, 4));
        bookings.add(new HotelBooking("Hilton", 150.60, 5));
    }

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public List<HotelBooking> getAll() {
        return bookings;
    }
}

BookingDemoApplication.java

代码语言:javascript
复制
package com.beniregev.bookingdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BookingDemoApplication {

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

}

我使用的是IntelliJ 2018.3、JDK 1.8.0_144和Springboot。当我运行服务器并转到"localhost:8080/bookings/all“而不是JSON时,我得到以下信息:

​

为什么列表不显示为JSON?我遗漏了什么?

我希望收到以下内容:

​

我会感谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-02 14:34:46

BookingController#getAll()方法返回将被转换为JSON有效负载的List。在客户端,您将看到它是一个JSON。它不会在JSONObject页面中神奇地显示为HTML变量。要做到这一点,您需要模板引擎。您还可以使用静态index.html文件在客户端播放您的API。从一开始就简单多了。

为此,您需要将内容添加到resources/static文件夹index.html文件中,内容如下:

代码语言:javascript
复制
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <title>Hotel bookings</title>
</head>
<body>
<h1>Hotel bookings</h1>
<table class="table">
    <thead>
    <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Number of nights</th>
        <th scope="col">Price per night</th>
        <th scope="col">Total price</th>
    </tr>
    </thead>
    <tbody class="bookingsBody"></tbody>
</table>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
        integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
        crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
        integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
        crossorigin="anonymous"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
    function laodAllHotelBookings() {
        var url = '/bookings/all/';
        var headers = {
            headers: {
                'Content-Type': 'application/json'
            }
        };
        axios.get(url, headers).then(res => {
            let bookingsBody = $('.bookingsBody');
            let data = res.data;
            $.each(Object.keys(data), function (index, key) {
                let item = data[key];
                var row = $('<tr>');
                row.append($('<th>').text(index));
                row.append($('<td>').text(item.hotelName));
                row.append($('<td>').text(item.pricePerNight));
                row.append($('<td>').text(item.numberOfNights));
                row.append($('<td>').text(item.totalPrice));

                bookingsBody.append(row);
            })
        }).catch(error => {
            console.log("error", error);
            const errorMsg = 'There was an error fetching the menu';
            console.log(errorMsg);
        });
    }

    laodAllHotelBookings();
</script>
</body>
</html>

若要application.properties文件,请添加以下行:

代码语言:javascript
复制
spring.resources.static-locations[0]=file:src/main/resources/static/

下面的内容应该可以在http://localhost:8080/下面看到:

​

在使用prices时,通常在Java中使用money时,总是使用BigDecimal。我已经修好了你的POJO

代码语言:javascript
复制
import java.math.BigDecimal;

public class HotelBooking {
    private String hotelName;
    private BigDecimal pricePerNight;
    private int numberOfNights;

    public HotelBooking(String hotelName, BigDecimal pricePerNight, int numberOfNights) {
        this.hotelName = hotelName;
        this.pricePerNight = pricePerNight;
        this.numberOfNights = numberOfNights;
    }

    public String getHotelName() {
        return hotelName;
    }

    public BigDecimal getPricePerNight() {
        return pricePerNight;
    }

    public int getNumberOfNights() {
        return numberOfNights;
    }

    public BigDecimal getTotalPrice() {
        return pricePerNight.multiply(BigDecimal.valueOf(numberOfNights));
    }
}

控制器构造函数如下所示:

代码语言:javascript
复制
public BookingController() {
    bookings = new ArrayList<>();

    bookings.add(new HotelBooking("Marriot", new BigDecimal("200.50"), 3));
    bookings.add(new HotelBooking("Novotel", new BigDecimal("140.74"), 1));
    bookings.add(new HotelBooking("Ibis", new BigDecimal("90.0"), 4));
    bookings.add(new HotelBooking("Hilton", new BigDecimal("150.60"), 5));
}

例如,inex.html使用了axios和bootstrap库。

票数 1
EN

Stack Overflow用户

发布于 2019-03-02 11:29:58

类HotelBooking需要是一个JavaBean。为了使它成为一个整体,它必须:

  1. 有一个没有参数的构造函数
  2. 拥有所有属性的getter和setter

因此,如果您将类更改为以下内容:

代码语言:javascript
复制
package com.beniregev.bookingdemo;

public class HotelBooking {
    private String hotelName;
    private double pricePerNight;
    private int numberOfNights;

    public HoterBooking() 
    {
    }

    public HotelBooking(String hotelName, double pricePerNight, int numberOfNights) {
        this.hotelName = hotelName;
        this.pricePerNight = pricePerNight;
        this.numberOfNights = numberOfNights;
    }

    public String getHotelName() {
        return hotelName;
    }

    public void setHotelName(String val) {
        this.hotelName = val;
    }

    public double getPricePerNight() {
        return pricePerNight;
    }

    public void setPricePerNight(double val) {
        this.pricePerNight = val;
    }

    public int getNumberOfNights() {
        return numberOfNights;
    }

    public void setNumberOfNights(int val) {
        this.numberOfNights = val;
    }

    public double getTotalPrica() {
        return pricePerNight * numberOfNights;
    }
}

它应该能像预期的那样起作用。

顺便说一下。不对货币值使用double类型。使用java.math.BigDecimal代替。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54957986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档