Spring Boot: как я могу проанализировать JSON, который состоит из массива объектов, и использовать переменную пути для получения указанного значения c? - PullRequest
0 голосов
/ 10 марта 2020

У меня есть следующая задача: мне нужно создать REST API Spring Boot, который считывает данные из файла JSON и позволяет пользователю фильтровать по цвету. URL должен выглядеть примерно так: http://localhost: 8080 / cars? Color = red Входные данные находятся во включенном файле JSON (cars. json). Они имеют вид:

{
"cars": [
    {
        "brand": "ford",
        "model": "fiesta",
        "fuel": "petrol",
        "doors": 5,
        "colour": "blue"
    }
]

}

I'm struggling to structurize JSON parsing classes properly, and here's my code



 import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.challenge.esure.service.MainService;

@RestController
public class MainController {

    private final MainService mainService;

    @Autowired
    public MainController(MainService mainService) {
        this.mainService = mainService;
    }

    @GetMapping("/all")
    public List<Cars> getAll() throws IOException {
        return mainService.getAllRecords();
    }

    @GetMapping("/cars?colour={colour}")
    public Cars getColour(@PathVariable("colour") String colour) throws IOException, ColourNotFoundException {
        return mainService.getCarColour(colour);
    }
}

// Служба:

    import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import com.challenge.esure.domain.CarDetails;
import com.challenge.esure.domain.Cars;
import com.challenge.esure.exceptions.ColourNotFoundException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class MainService {

    public List<Cars> getData() throws IOException{

        Resource resource = new ClassPathResource("cars.json");
        InputStream input = resource.getInputStream();
        File file = resource.getFile();
        ObjectMapper objectMapper = new ObjectMapper();


        List<Cars> car = Arrays.asList(objectMapper.readValue(file, Cars[].class));
            return car.stream().collect(Collectors.toList());

    }

    public List<Cars> getAllRecords() throws IOException {
        return getData();
    }

    public Cars getCarColour(String colour) throws ColourNotFoundException, IOException {
        return getData().stream()
                .filter(Cars -> Cars.getColour().equals(colour))
                .findAny()
                .orElseThrow(() -> new ColourNotFoundException("We don't have cars with that colour"));

    } 

}

// Домен

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Cars {

    private ArrayList<Object> cars;
    private String brand;
    private String model;
    private String fuel;
    private Integer doors;
    private String colour;

    public Cars() {

    }

    public Cars(ArrayList<Object> cars, String brand, String model, String fuel, Integer doors, String colour) {
        this.cars = cars;
        this.brand = brand;
        this.model = model;
        this.fuel = fuel;
        this.doors = doors;
        this.colour = colour;
    }

    public ArrayList<Object> getCars() {
        return cars;
    }

    public void setCars(ArrayList<Object> cars) {
        this.cars = cars;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getFuel() {
        return fuel;
    }

    public void setFuel(String fuel) {
        this.fuel = fuel;
    }

    public Integer getDoors() {
        return doors;
    }

    public void setDoors(Integer doors) {
        this.doors = doors;
    }

    public String getColour() {
        return colour;
    }

    public void setColour(String colour) {
        this.colour = colour;
    }


}

// Исключение

   public class ColourNotFoundException extends Exception {
    public ColourNotFoundException(String what) {
        super(what);
    }
}

1 Ответ

0 голосов
/ 10 марта 2020

Вы можете использовать следующую структуру данных

@JsonIgnoreProperties(ignoreUnknown = true)
public class CarResponse {
    List<Car> cars;

    public List<Car> getCars() {
        return cars;
    }

    public void setCars(List<Car> cars) {
        this.cars = cars;
    }

    @Override
    public String toString() {
        return "CarResponse{" +
                "cars=" + cars +
                '}';
    }
}
public class Car {
    private String brand;
    private String model;
    private String fuel;
    private Integer doors;
    private String colour;
}
CarResponse carResponse= objectMapper.readValue(jsonString, CarResponse.class);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...