- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个返回 JSONArray 的方法。现在我想用我的 Spring Boot Rest Controller 返回 JSONArray,但它只在我的浏览器中重新运行“{“empty”:false}”。
希望您能理解我的问题。
感谢您的帮助。
来自德国的问候:D
尼古拉斯
我尝试返回一个列表,但以同样的方式结束。
我的休息 Controller
package eliteDangerousRestService.restController;
import java.util.List;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import eliteDangerousRestService.restApplications.commodity.GetStationWithSpecificCommodity;
@RestController
public class Controller
{
@RequestMapping( value = "/elite-dangerous/commodity", method = RequestMethod.GET )
@ResponseBody
public List<JSONObject> getCommodity
(
@RequestParam( value = "currentSystem", defaultValue = "Sol" ) String currentSystenName,
@RequestParam( value = "radius", defaultValue = "30" ) Integer radius,
@RequestParam( value = "inklSystemsWithPermission", required = false, defaultValue = "false" ) Boolean inkSystemsWithPermission,
@RequestParam( value = "inkPlanetrayStations", required = false, defaultValue = "false" ) Boolean inkPlanetrayStations,
@RequestParam( value = "commodityName", required = false, defaultValue = "$Gold_Name" ) String commodityName,
@RequestParam( value = "count", required = false, defaultValue = "10" ) Integer count,
@RequestParam( value = "multi", required = false, defaultValue = "2" ) Double multiplayer,
@RequestParam( value = "maxAge", required = false, defaultValue = "15" ) Integer maxAge
)
{
System.out.println( currentSystenName );
System.out.println( radius );
System.out.println( inkSystemsWithPermission );
System.out.println( inkPlanetrayStations );
System.out.println( commodityName );
System.out.println( count );
System.out.println( multiplayer );
System.out.println( maxAge );
GetStationWithSpecificCommodity getStationWithSpecificCommodity = new GetStationWithSpecificCommodity();
List<JSONObject> list = getStationWithSpecificCommodity.getAllData( currentSystenName, radius,
inkSystemsWithPermission, inkPlanetrayStations, commodityName, count, multiplayer, maxAge );
System.out.println( list.toString() );
return list;
}
}
构建列表的我的类
package eliteDangerousRestService.restApplications.commodity;
import static eliteDangerousRestService.restApplications.commodity.SQLConstants.SQL_SELECT_CURRENT_SYSTEM;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import eliteDangerousRestService.functions.DatabaseHandler;
import eliteDangerousRestService.functions.SystemLogger;
public class GetStationWithSpecificCommodity
{
SystemLogger systemLogger = SystemLogger.getInstance();
String className = this.getClass().getSimpleName();
DatabaseHandler databaseHandler = DatabaseHandler.getInstance();
CommodityMapping commodityMapping = new CommodityMapping();
ResultSet rsos = null;
public List<JSONObject> getAllData( String currentSystemName, int radius, boolean inkSystemsWithPermissions,
boolean inkPlanetaryStations,
String commodityName, int count, double multiplayer, int maxAge )
{
Helper helper = new Helper();
Defaults defaults = new Defaults();
JSONArray jsonArraySystems = new JSONArray();
JSONArray jsonArrayStations = new JSONArray();
int minSupply = helper.minSupplyCalc( defaults.defaultCount( count ),
defaults.defaultMultiplayer( multiplayer ) );
int commodityID = commodityMapping.mapping( commodityName );
long maxCommodityAge = helper.maxAgeHelper( defaults.defaultsMaxAge( maxAge ) );
Connection connection = databaseHandler.connect();
try (PreparedStatement pscs = connection.prepareStatement( SQL_SELECT_CURRENT_SYSTEM ))
{
pscs.setString( 1, currentSystemName );
ResultSet rscs = pscs.executeQuery();
float x_pos = rscs.getFloat( "x_pos" );
float y_pos = rscs.getFloat( "y_pos" );
float z_pos = rscs.getFloat( "z_pos" );
boolean currentSystemPermit = rscs.getBoolean( "needs_permit" );
String sqlOtherSystems = helper.buildStatement(
defaults.defaultsInkSystemsWithPermission( inkSystemsWithPermissions, currentSystemPermit ),
inkPlanetaryStations );
try (PreparedStatement psos = connection.prepareStatement( sqlOtherSystems ))
{
psos.setInt( 1, commodityID );
psos.setInt( 2, minSupply );
psos.setLong( 3, maxCommodityAge );
rsos = psos.executeQuery();
long lastSystemID = 0;
while( rsos.next() )
{
float x_pos2 = rsos.getFloat( "x_pos" );
float y_pos2 = rsos.getFloat( "y_pos" );
float z_pos2 = rsos.getFloat( "z_pos" );
double x = x_pos - x_pos2;
double y = y_pos - y_pos2;
double z = z_pos - z_pos2;
double result = Math.sqrt( Math.pow( x, 2 ) + Math.pow( y, 2 ) + Math.pow( z, 2 ) );
if( result <= defaults.defaultsRadius( radius ) )
{
long systemID = rsos.getLong( "system_id" );
if( lastSystemID == systemID )
{
lastSystemID = rsos.getLong( "system_id" );
}
else
{
jsonArraySystems.put( buildJSONObjectSystem( result ) );
lastSystemID = rsos.getLong( "system_id" );
}
jsonArrayStations.put( buildJSONObjectStation() );
}
}
}
catch( SQLException e )
{
e.printStackTrace();
}
}
catch( SQLException e )
{
systemLogger.info( className, e.getMessage() );
}
JSONArray sortedArraySystems = sort( jsonArraySystems, "Distance" );
//JSONArray finalArray = map( sortedArraySystems, jsonArrayStations );
List<JSONObject> finalArray = map( sortedArraySystems, jsonArrayStations );
systemLogger.info( className, finalArray.toString() );
return finalArray;
}
public JSONObject buildJSONObjectSystem( double result ) throws SQLException
{
JSONObject jsonObjectSystem = new JSONObject();
jsonObjectSystem.put( "SystemName", rsos.getString( "system_name" ) );
jsonObjectSystem.put( "Distance", result );
jsonObjectSystem.put( "NeedsPermit", rsos.getBoolean( "needs_permit" ) );
jsonObjectSystem.put( "CommodityID", rsos.getInt( "commodity_id" ) );
return jsonObjectSystem;
}
public JSONObject buildJSONObjectStation() throws SQLException
{
JSONObject jsonObjectStation = new JSONObject();
jsonObjectStation.put( "StationName", rsos.getString( "station_name" ) );
jsonObjectStation.put( "SystemName", rsos.getString( "system_name" ) );
jsonObjectStation.put( "LandingPadSize", rsos.getString( "max_landing_pad_size" ) );
jsonObjectStation.put( "DistanceToStar", rsos.getLong( "distance_to_star" ) );
jsonObjectStation.put( "MarketUpdatedAt", rsos.getLong( "market_updated_at" ) );
jsonObjectStation.put( "Planetary", rsos.getBoolean( "is_planetary" ) );
jsonObjectStation.put( "Supply", rsos.getLong( "supply" ) );
jsonObjectStation.put( "BuyPrice", rsos.getInt( "buy_price" ) );
jsonObjectStation.put( "SellPrice", rsos.getInt( "sell_price" ) );
jsonObjectStation.put( "Demand", rsos.getLong( "demand" ) );
return jsonObjectStation;
}
public List<JSONObject> map( JSONArray jsonArraySystems, JSONArray jsonArrayStations )
{
JSONArray jsonArray = new JSONArray();
List<JSONObject> list = new ArrayList<>( );
for( int system = 0; system < jsonArraySystems.length(); system++ )
{
String key = jsonArraySystems.getJSONObject( system ).getString( "SystemName" );
JSONObject systemArray = new JSONObject();
JSONArray stationArray = new JSONArray();
for( int station = 0; station < jsonArrayStations.length(); station++ )
{
String value = jsonArrayStations.getJSONObject( station ).getString( "SystemName" );
if( key.equals( value ) )
{
stationArray.put( jsonArrayStations.getJSONObject( station ) );
}
}
systemArray.put( "General", jsonArraySystems.get( system ) );
// Before Inserting SationArray Sort Stations.
systemArray.put( "Stations", sort( stationArray, "DistanceToStar" ) );
//jsonArray.put( systemArray );
list.add( systemArray );
}
return list;
//return jsonArray;
}
public JSONArray sort( JSONArray jsonArray, String searchParam )
{
List<JSONObject> sortedArray = new ArrayList<JSONObject>();
for( int i = 0; i < jsonArray.length(); i++ )
sortedArray.add( jsonArray.getJSONObject( i ) );
Collections.sort( sortedArray, ( jsonObjectA, jsonObjectB ) -> {
int compare = 0;
try
{
Double keyA = jsonObjectA.getDouble( searchParam );
Double keyB = jsonObjectB.getDouble( searchParam );
compare = Double.compare( keyA, keyB );
}
catch( JSONException e )
{
e.printStackTrace();
}
return compare;
} );
JSONArray sortedJSONArray = new JSONArray();
for( int i = 0; i < sortedArray.size(); i++ )
{
sortedJSONArray.put( sortedArray.get( i ) );
}
return sortedJSONArray;
}
}
在控制台中,代码如下所示,这就是我希望通过 RestApi 返回它的方式。
[
{
"Stations": [
{
"Demand": 0,
"StationName": "Daedalus",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550116514,
"DistanceToStar": 196,
"Planetary": false,
"Supply": 68929,
"SellPrice": 8887,
"SystemName": "Sol",
"BuyPrice": 9079
},
{
"Demand": 0,
"StationName": "Burnell Station",
"LandingPadSize": "M",
"MarketUpdatedAt": 1550116815,
"DistanceToStar": 359,
"Planetary": false,
"Supply": 445,
"SellPrice": 9344,
"SystemName": "Sol",
"BuyPrice": 9545
},
{
"Demand": 0,
"StationName": "Galileo",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550087622,
"DistanceToStar": 502,
"Planetary": false,
"Supply": 46218,
"SellPrice": 9057,
"SystemName": "Sol",
"BuyPrice": 9252
},
{
"Demand": 0,
"StationName": "Columbus",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550099829,
"DistanceToStar": 2493,
"Planetary": false,
"Supply": 295,
"SellPrice": 9831,
"SystemName": "Sol",
"BuyPrice": 10044
},
{
"Demand": 0,
"StationName": "Titan City",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550095558,
"DistanceToStar": 5040,
"Planetary": false,
"Supply": 191,
"SellPrice": 9680,
"SystemName": "Sol",
"BuyPrice": 9890
}
],
"General": {
"CommodityID": 42,
"SystemName": "Sol",
"NeedsPermit": true,
"Distance": 0
}
},
{
"Stations": [
{
"Demand": 0,
"StationName": "al-Din Prospect",
"LandingPadSize": "M",
"MarketUpdatedAt": 1550116804,
"DistanceToStar": 5586,
"Planetary": false,
"Supply": 341,
"SellPrice": 9831,
"SystemName": "Alpha Centauri",
"BuyPrice": 9945
},
{
"Demand": 0,
"StationName": "Hutton Orbital",
"LandingPadSize": "M",
"MarketUpdatedAt": 1550115464,
"DistanceToStar": 6397048,
"Planetary": false,
"Supply": 24,
"SellPrice": 9831,
"SystemName": "Alpha Centauri",
"BuyPrice": 9945
}
],
"General": {
"CommodityID": 42,
"SystemName": "Alpha Centauri",
"NeedsPermit": false,
"Distance": 4.377120022057882
}
},
{
"Stations": [
{
"Demand": 0,
"StationName": "Levi-Strauss Installation",
"LandingPadSize": "M",
"MarketUpdatedAt": 1550069914,
"DistanceToStar": 6,
"Planetary": false,
"Supply": 1836,
"SellPrice": 9444,
"SystemName": "Barnard's Star",
"BuyPrice": 9557
},
{
"Demand": 0,
"StationName": "Miller Depot",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550111992,
"DistanceToStar": 38,
"Planetary": false,
"Supply": 93,
"SellPrice": 9831,
"SystemName": "Barnard's Star",
"BuyPrice": 9946
},
{
"Demand": 0,
"StationName": "Boston Base",
"LandingPadSize": "L",
"MarketUpdatedAt": 1550116825,
"DistanceToStar": 62,
"Planetary": false,
"Supply": 48,
"SellPrice": 9831,
"SystemName": "Barnard's Star",
"BuyPrice": 9945
}
],
"General": {
"CommodityID": 42,
"SystemName": "Barnard's Star",
"NeedsPermit": false,
"Distance": 5.954662695107087
}
},
.
.
.
.
and so on.
最佳答案
鉴于您正在尝试返回 RESTful 响应,我建议返回一个 ResponseEntity,其中包含响应正文中的列表。
@RequestMapping( value = "/elite-dangerous/commodity", method = RequestMethod.GET )
@ResponseBody
public ResponseEntity<?> getCommodity
(
@RequestParam( value = "currentSystem", defaultValue = "Sol" ) String currentSystenName,
@RequestParam( value = "radius", defaultValue = "30" ) Integer radius,
@RequestParam( value = "inklSystemsWithPermission", required = false, defaultValue = "false" ) Boolean inkSystemsWithPermission,
@RequestParam( value = "inkPlanetrayStations", required = false, defaultValue = "false" ) Boolean inkPlanetrayStations,
@RequestParam( value = "commodityName", required = false, defaultValue = "$Gold_Name" ) String commodityName,
@RequestParam( value = "count", required = false, defaultValue = "10" ) Integer count,
@RequestParam( value = "multi", required = false, defaultValue = "2" ) Double multiplayer,
@RequestParam( value = "maxAge", required = false, defaultValue = "15" ) Integer maxAge
)
{
System.out.println( currentSystenName );
System.out.println( radius );
System.out.println( inkSystemsWithPermission );
System.out.println( inkPlanetrayStations );
System.out.println( commodityName );
System.out.println( count );
System.out.println( multiplayer );
System.out.println( maxAge );
GetStationWithSpecificCommodity getStationWithSpecificCommodity = new GetStationWithSpecificCommodity();
List<JSONObject> list = getStationWithSpecificCommodity.getAllData( currentSystenName, radius,
inkSystemsWithPermission, inkPlanetrayStations, commodityName, count, multiplayer, maxAge );
System.out.println( list.toString() );
return ResponseEntity.ok(list);
}
编辑:
在处理 api 数据时,我建议采用模型模式并使用 Jackson 作为 POJO 到 JSON 的序列化/反序列化器。截至目前,您正在尝试自己构建 JSON 响应。我不认为你所做的事情是错误的,我只是认为这使事情变得复杂并且对你来说增加了更多的开销。如果您创建了一个响应模型,您的 List 将是 List,然后您的 ResponseBody 将包含它。
现在,您的列表似乎包含空/空数据。我将继续探索,看看是否可以找到针对您的实现的特定答案。
关于java - 如何使用 Spring Boot Rest Controller 返回 JSONArray?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54712998/
有人可以解释一下 spring-boot-parent 和 spring-boot-starter-parent 之间的区别吗,正如我在下面附加的 GIT HUB 代码链接之一中看到的,他们为 spr
我有与 jersey 框架集成的 Spring Boot 应用程序。 现在,当我尝试运行该应用程序时,它只是停留在 Spring 启动徽标上,之后没有任何 react 。 我也尝试添加 -X ,但徽标
我指的是 Spring Boot 关于 的文档自动配置 和 执行器 模块: 自动配置: Spring Boot AutoConfiguration attempts to automatically
我正在尝试将 apache log4j 集成到我的 Spring boot 应用程序中。这是我的 build.gradle 文件: build.gradle buildscript { rep
使用 Spring Boot Maven 插件的以下命令在生产中启动 Spring Boot 应用程序是否是一个好主意或实践? mvn spring-boot:run 最佳答案 不,这是个坏主意。 您
据我所知,spring boot 和 spring session 为我们提供了一站式自动配置,但是当我的应用程序使用 session redis 和应用程序缓存 redis 时,不是同一个 redi
我希望使用Spring Boot创建一个新的Web应用程序。不幸的是,我的服务器在技术堆栈方面相当有限。它安装了Java 5。 谁能告诉我spring boot是否可以在Java 1.5上运行以及什么
我有3个实体 CarWash(设置Wash) Wash(car_wash_id FK到CarWash) WashComment(wash_id FK到Wash) 有什么办法可以写这个查询 @Qu
我一直在关注this文章。 我正在尝试在Spring-boot应用程序中优雅地处理gRPC错误,的主要目标是能够在gRPC客户端中获取错误状态。 在上面的文章之后,我坚持为异常添加拦截器。如何在Spr
我有一个要使用的自定义log4j布局插件。在IntelliJ中运行或与./gradlew bootRun一起运行时,插件可以正常工作。不使用./gradlew bootJar构建启动jar。 启用-D
我想在给定范围 (5001-5100) 的随机端口上启动 Spring Cloud 应用程序(Spring Boot 1.5.14,Spring Cloud Edgware.SR4)。我知道我们可以使
任何人都可以向我展示或指出不使用 spring boot gradle 插件的 spring boot gradle 项目。 我正在寻找类似不使用 gradle 插件的 spring boot sta
我当时尝试包含上述依赖项之一,但找不到任何区别: spring boot starter web:我可以看到 Flux 和 Mono 类并制作一个响应式(Reactive)休息 Controller
我们一直在为我们的应用程序使用 Springboot 1.X。 现在准备开始一些新的应用程序,想知道我们是应该使用 SpringBoot2.0 还是坚持使用 SpringBoot 1.X? 对一种方式
我希望记录应用程序正在加载 application-profile.propeties 或 application.yml。怎么做。在哪种方法中,我可以听取它并检测它是成功加载还是失败。 最佳答案 您
当我在 pom.xml 中添加简单的 spring-boot-starter-data-jpa 依赖项时,在 pom.xml 文件中出现错误。如果我删除该依赖项,则不会再有错误。我不确定为什么会发生这
我希望记录应用程序正在加载 application-profile.propeties 或 application.yml。怎么做。在哪种方法中,我可以听取它并检测它是成功加载还是失败。 最佳答案 您
我在网上看了很多关于 spring-boot-devtools 的文章和问题,但仍然无法弄清楚为什么它对我不起作用。每次运行我的应用程序时,我都会得到以下信息: 17:54:28.057 [main]
我正在尝试将现有的 Spring 应用程序移植到 Spring Boot。我不使用 spring-boot-starter-data-solr 启动器,但是我的类路径上有 apache solrj (
(这主要是一个历史问题。Pivotal 建议所有论坛讨论都在 StackOverflow 上进行,这就是我在这里问它的原因。) Spring Boot 项目用来证明将应用程序的类和依赖项从可执行 ja
我是一名优秀的程序员,十分优秀!