springboot學習-返回JSON數據

JSON是目前主流的前後端數據傳輸方式,SpringMVC中使用消息轉換器HttpMessageConverter對JSON的轉換提供了很好的支持,在SpringBoot中更進一步,對相關配置做了更進一步的簡化。默認情況下,當開發者新創建一個SpringBoot項目後,添加Web依賴,代碼如下:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

創建BookJson實體類:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;

import java.util.Date;

public class BookJson {
    private String name;
    private String author;
    @JsonIgnore
    private Float price;
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date publicationDate;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public Date getPublicationDate() {
        return publicationDate;
    }

    public void setPublicationDate(Date publicationDate) {
        this.publicationDate = publicationDate;
    }
}

然後創建BookJsonController,返回bookjson對象即可:
 

import com.sang.enity.BookJson;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController          //@RestController = @Controller + @ResponseBody
public class BookJsonController {
    @RequestMapping("/books")
    public BookJson books() {
        BookJson booksjson = new BookJson();
        booksjson.setAuthor("李玉");
        booksjson.setName("自學springboot");
        booksjson.setPrice(30f);
        booksjson.setPublicationDate(new Date());
        return booksjson;
    }
}

然後在瀏覽器中進行訪問:

JSON處理器可以使用一些開源JSON解析框架,我使用的是默認的

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章