- 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/
我正在使用网络服务请求直方图数据。数据是数组中的一组数组: [[1375056000000,23.284713745117],[1375142400000,3.809531211853], [1375
这是我的 json 文件的相关部分: "categories": [ [ "Belgian Restaurant", "belgian" ],
我目前很困惑,为什么我不能在我的 Android 应用程序中从 JSONArray 中提取 JSONArray。下面给出了一个示例和我的源代码片段。 //The JSON { "cur
我正在尝试解析 JSONObject。 这个 JSONObject 中有一个 JSONArray,它在 JSONArray 中还有另一个 JSONArray。 我试图解析的 json 形式如下。 {
我正在尝试解析对象数据列表中的 JSON 数组 payment_details。 在这里,我已经成功解析了回收站 View 中调用的数据数组,但我无法调用 payment_details 数组。 适配
我正在寻找一个选项,可以将多个值添加到 JSONArray 并将其添加到另一个 JSONArray 中,而无需创建多个变量。例如: JSONArray array1 = new JSONArr
我遇到过一种情况,org.json.JSONArray 对象非常大,这最终会导致延迟和其他问题。因此,我们决定将 JSONArray 分割成更小的 block 。例如,如果 JSONArray 是这样
您好,我正在尝试在另一个 json 数组中解析一个 json 数组。帮我解决这个问题。 我的 Json 数组是 "results":[ { "percentcompleted"
我正在使用 Gson用于解析 json 响应。我需要在 JsonArray 中解析 JSONArry.. 我的回答是.. { "message": "Retreive sucessfully", "f
@GET @Produces("application/json") public Response GetAll() throws JSONException{ tblCategoryDao
我从服务器获取以下 json: { "Data": [ { "Record": [ " d11", "d12"
我正在使用 ajax 将 json 对象从 javascript 传递到 java servlet。 var jsonObj = JSON.stringify(objArray); //Then I
我需要获取作为“结果”内部数组的“示例”数据 JSON FILE 并将其附加到字符串。最简单的方法是什么? 这就是我得到“定义”的方式 private JSONObject queryResults;
我需要从 JSONArray 获取 JSONArray: JSONParser parser = new JSONParser(); JSONObject jObject=(J
我有一个 jsonArray 响应。我需要阅读此响应,其中包含 3 个 jsonArray。 这是 json 响应。这是一个 GET 请求并通过 Volley 请求发送。 [ "0x9000",
在此 Json 响应中,如何使用 Java 访问“smallImageUrls”并获取图像 url? 似乎“smallImageUrls”是“匹配”jsonarray 中的一个数组。如果我错了,请有人
这个问题在这里已经有了答案: Convert string to JSON array (10 个答案) 关闭 5 年前。 如何正确地将此字符串转换为 jsonArray? { "myArr
是否可以从较新的 EJB JSON 库转换为较旧的 org.json 库,而无需依赖 org.json.simple 或 GSON? 在下面的例子中,“buttons”是一个填充的 JsonArr
如何从jsonarray获取jsonarray? 我试过的代码。 for(loop) List stringList = new ArrayLis
我目前是 Json 新手,遇到了一个问题。我搜索了很多但找不到答案! 我从 json url 获取名称列表。名称可以在此 json 文件中重复,但我只想将它们的一条记录保留到我称为“arr”的新数组中
我是一名优秀的程序员,十分优秀!