【发布时间】:2021-11-16 13:16:21
【问题描述】:
我正在运行一个简单的 Spring Boot 应用程序,该应用程序从 MySQL 数据库中检索国家/地区的详细信息。我在运行应用程序时得到的初始响应是 json 格式的。但是,在 application.properties 文件中进行了一些编辑后,我现在可以在 XML 中获得响应。有什么方法可以恢复到 json 响应?此应用程序是我尝试使用 Spring 云网关和 Eureka 服务器构建的微服务应用程序的一部分。
application.properties
spring.jpa.hibernate.ddl-auto = update
spring.datasource.url= jdbc:mysql://localhost:3306/countries-microservice
spring.datasource.username= root
spring.datasource.password=
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.application.name=countries-service
server.port=3001
eureka.client.serviceUrl.defaultZone=http://localhost:3000/eureka/
CountryRepository.java
package com.example.countriesservice.repository;
import com.example.countriesservice.model.Country;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CountryRepository extends JpaRepository<Country, String> {
Country findByCountry(String country);
}
CountryService.java
package com.example.countriesservice.service;
import java.util.List;
import com.example.countriesservice.model.Country;
import com.example.countriesservice.repository.CountryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CountryService {
private final CountryRepository countryRepository;
@Autowired
public CountryService(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
public List<Country> getAllCountries() {
return countryRepository.findAll();
}
public Country getCountry(String country) {
return countryRepository.findByCountry(country);
}
}
CountryController.java
package com.example.countriesservice.controller;
import com.example.countriesservice.service.CountryService;
import java.util.List;
import com.example.countriesservice.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/countries")
@RestController
public class CountryController {
private final CountryService countryService;
@Autowired
public CountryController(CountryService countryService) {
this.countryService = countryService;
}
@GetMapping("/getAll")
public List<Country> getAll() {
return countryService.getAllCountries();
}
@GetMapping("/{country}")
public Country getCountry(@PathVariable String country) {
return countryService.getCountry(country);
}
}
由于我仍在学习 Spring Boot,如果您能详细解释一下我做错了什么以及如何更正它,那就太好了。
【问题讨论】:
-
您可能请求的是 XML 而不是 JSON。
-
将您的请求更改为请求 JSON 而不是 XML。您发布的代码与它无关。
-
您必须将 Accept 标头设置为 application/json developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept
标签: java spring spring-boot jpa