【问题标题】:Gradle Spring Boot Application Failed to Extract Data from Json fileGradle Spring Boot 应用程序无法从 Json 文件中提取数据
【发布时间】:2022-01-20 11:36:01
【问题描述】:

我创建了带有 spring boot 依赖项的 Gradle 项目,这是一个 rest api。我默认使用 netbeans 版本 12.6 和 java 17。应用程序运行在端口号 8080 和 tomcat 服务器上。我想在调用其余 api 方法时将数据显示到 localhost,但主要问题是当我尝试调用 instance.http://localhost:8080/result/2 方法时。它显示以下错误消息。

{"error":"not-found-001","message":"2 not found"}

这是 jason 文件。

{
    "id": 16,
    "name": "Arfon",
    "seqNo": 2,
    "partyResults": [
        {
            "party": "LAB",
            "votes": 8484,
            "share": 33.90
        },
        {
            "party": "PC",
            "votes": 8028,
            "share": 32.10
        },
        {
            "party": "CON",
            "votes": 4106,
            "share": 16.40
        },
        {
            "party": "LD",
            "votes": 3942,
            "share": 15.70
        },
        {
            "party": "UKIP",
            "votes": 482,
            "share": 1.90
        },
        {
            "party": "OTH",
            "votes": 0,
            "share": 0.00
        }
    ]
}

这是主类代码。

@SpringBootApplication
public class ElectionsApiApplication {
    

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

}

这里是存储库。

@Component
public class MapBasedRepository implements ResultService {

    private final Map<Integer,ConstituencyResult> results;

    public MapBasedRepository() {
        results = new ConcurrentHashMap<>();
    }

    @Override
    public ConstituencyResult GetResult(Integer id) {
        return results.get(id);
    }

    @Override
    public void NewResult(ConstituencyResult result) {
        results.put(result.getId(), result);
    }

    @Override
    public Map<Integer, ConstituencyResult> GetAll() {
        return results;
    }

    @Override
    public void reset() {
        results.clear();
    }

    @Override
    public Scoreboard soreboardResult(Scoreboard scoreboard) {
        return scoreboard;
     }

   

   
}

这是控制器代码。

@RestController
public class ResultsController {

    private final ResultService results;

    public ResultsController(ResultService resultService) {
        this.results = resultService;
    }

    @GetMapping("/result/{id}")
    ConstituencyResult getResult(@PathVariable Integer id) {
        ConstituencyResult result = results.GetResult(id);
        if (result == null) {
            throw new ResultNotFoundException(id);
        }
        return results.GetResult(id);
    }

    @PostMapping("/result")
    ResponseEntity<String> newResult(@RequestBody ConstituencyResult result) {
        if (result.getId() != null) {
            results.NewResult(result);
            return ResponseEntity.created(URI.create("/result/"+result.getId())).build();
        }
        return ResponseEntity.badRequest().body("Id was null");
    }

    @GetMapping("/scoreoard")
   Scoreboard soreboardResult(Scoreboard scoreboard) {
        if(scoreboard==null){
            throw new ResultNotFoundException();
        }
       
        return new Scoreboard();
    }
}

这里是异常处理类。

@RestControllerAdvice
public class ResultsExceptionHandler {

    @ExceptionHandler(ResultNotFoundException.class)
    public ResponseEntity<ApiResponse> handleNotFoundApiException(
            ResultNotFoundException ex) {
        ApiResponse response =
                ApiResponse.builder()
                        .error("not-found-001")
                        .message(String.format("%d not found",ex.getId()))
                        .build();
        return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(NotImplementedException.class)
    public ResponseEntity<ApiResponse> handleNotImplementedApiException(
            NotImplementedException ex) {
        ApiResponse response =
                ApiResponse.builder()
                        .error("not-implemented-002")
                        .message("Function not yet implemented")
                        .build();
        return new ResponseEntity<>(response, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

这是测试代码。

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ElectionsApiApplicationIntegrationTests {
    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private TestRestTemplate template;

    @Autowired
    private ResultService resultService;

    @BeforeEach
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @AfterEach
    public void reset() throws Exception {
        resultService.reset();
    }


    @Test
    public void first5Test() throws Exception {
        Scoreboard scoreboard = runTest(5);

        assertNotNull(scoreboard);
               //Scoreboard sc = objectMapper.readValue(new File(".\\result001.json"), Scoreboard.class);
              //  System.out.println(sc);  
            
            
        // assert LD == 1
        // assert LAB = 4
        // assert winner = noone
            
    }

    @Test
    public void first100Test() throws Exception {
        Scoreboard scoreboard = runTest(100);

        assertNotNull(scoreboard);
        // assert LD == 12
        // assert LAB == 56
        // assert CON == 31
        // assert winner = noone
    }

    @Test
    public void first554Test() throws Exception {
        Scoreboard scoreboard = runTest(554);

        assertNotNull(scoreboard);
        // assert LD == 52
        // assert LAB = 325
        // assert CON = 167
        // assert winner = LAB
    }

    @Test
    public void allTest() throws Exception {
        Scoreboard scoreboard = runTest(650);

        assertNotNull(scoreboard);
        // assert LD == 62
        // assert LAB == 349
        // assert CON == 210
        // assert winner = LAB
        // assert sum = 650
    }


    private Scoreboard runTest(int numberOfResults) throws Exception {
        for (int i = 1; i <= numberOfResults; i++ ) {
            Class<?> clazz  = this.getClass();
            InputStream is = clazz.getResourceAsStream(String.format("/sample-election-results/result%s.json",String.format("%03d",i)));
            ConstituencyResult cr = objectMapper.readValue(is, ConstituencyResult.class);
            template.postForEntity(base.toString()+"/result", cr,String.class);
        }
        ResponseEntity<Scoreboard> scores = template.getForEntity(base.toString()+"/scoreboard", Scoreboard.class);
        return scores.getBody();
    }
}

【问题讨论】:

    标签: java spring-boot gradle netbeans spring-rest


    【解决方案1】:

    请求路径是 http://localhost:8080/result/2 ,这是在查询 id = 2 ,它在您的 json 文件中不存在。此文件仅包含 id = 16

    【讨论】:

    • 同样的错误。 id 16
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 2023-03-13
    • 2020-11-10
    • 2021-02-20
    • 2018-02-19
    • 2014-10-12
    • 2017-06-26
    相关资源
    最近更新 更多