如何使用Spring Boot Rest Controller返回JSONArray?

时间:2019-02-15 16:05:46

标签: java spring rest spring-boot

我有一个返回JSONArray的方法。 现在,我想用Spring Boot Rest Controller返回该JSONArray,但它只在浏览器中重新运行“ {“ empty”:false}“。

希望您能理解我的问题。

感谢您的帮助。

来自德国的问候:D

尼古拉斯

我试图返回一个List,但该尾码的返回方式相同。

我的RestController

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.

1 个答案:

答案 0 :(得分:1)

鉴于您尝试返回一个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数据时,我建议采用Model模式,并使用Jackson作为POJO到JSON的序列化/反序列化器。截至目前,您正在尝试自己构建JSON响应。我不认为您正在做的事情是错误的,我只是认为这会使事情变得复杂,并且给您带来更多开销。如果您创建了一个响应模型,则您的列表将为List,然后您的ResponseBody将包含该模型。

现在,您的列表似乎包含空/空数据。我将继续四处查看,是否可以找到针对您的实现的答案。