我有一个简单的 Spring Web 应用程序,我尝试返回 json 作为响应,但我不知道为什么以及如何它应该将 json 输出返回到 .我在这里做错了什么?
package com.restservice.restservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RestserviceApplication {
public static void main(String[] args) {
SpringApplication.run(RestserviceApplication.class, args);
}
}
package com.restservice.restservice;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import javax.print.attribute.standard.Media;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import static java.time.LocalTime.now;
@RestController
public class MainController {
@GetMapping(value = "/stocks/{symbol}" ,produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux prices(@PathVariable String symbol) {
return Flux.interval(Duration.ofSeconds(1))
.map(stockprice -> new StockPrice(symbol, getRandomStockPrice(),now()));
}
private static Double getRandomStockPrice() {
return ThreadLocalRandom.current().nextDouble(100.0);
}
}
package com.restservice.restservice;
import java.time.LocalTime;
public class StockPrice {
public StockPrice() {
}
public StockPrice(String symbol, double randomStockPrice, LocalTime now) {
}
}
我现在如何将 StockPrice 字符串符号、双 randomStockPrice、LocalTime 作为格式化 json 打印到网络上?
您刚刚调用了构造。你必须吸收构造函数中传入的值。您现在需要在 StockPrice 类中创建变量符号 randomStockPrice。然后你需要将构造函数中的值设置为等于它们
这样
public class StockPrice {
String symbol;
double randomStockPrice;
LocalTime now;
public StockPrice() {
}
public StockPrice(String symbol, double randomStockPrice, LocalTime now) {
this.symbol = symbol;
this.randomStockPrice = randomStockPrice;
this.now = now;
}
}