1

i hava a method that is returning a JSONArray. Now i want to return that JSONArray with my Spring Boot Rest Controller but it only retruns "{"empty":false}" this in my Browser.

I hope that you can understand my problem.

Thanks for helping.

Greetings from Germany:D

Niclas

I tried to return a List but that endet the same way.

My 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;

    }
}

My Class that builds the 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;
    }
}



In the Console the code looks like this, and this is how i want to return it by the 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 Answer 1

3

Given that you are trying to return a RESTful response, I'd recommend returning a ResponseEntity with the list within the body of the response.

    @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);

}

EDIT:

I would recommend adopting the Model pattern and using Jackson as a serializing/deserializer for POJO's to JSON when it comes to working with your api data. As of right now, you're trying to construct your JSON response yourself. I don't think what you're doing is wrong, I just think it complicates things and it's more overhead for you. If you created a response model, your List would be List and then your ResponseBody would contain that.

Right now, it looks like your list is containing null/empty data. I'll continue to poke around to see if I can find an answer specific to your implementation.

Sign up to request clarification or add additional context in comments.

2 Comments

HI Brandon thanks for your answer. Now my Response looks like this:[{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},]
Thanks for helping me out. Niclas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.