Click here to Skip to main content
15,890,670 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am fairly new to APIs and I am trying to run a query that will always just return 1 result. I have some code that works but it is using List<> so when the JSON is returned I get square brackets, eg.

[
    {
        "customer": 43563254,
        "points": 14
    }
]


As it's just one result I want to return without the square brackets. What is the best way to achieve this?

What I have tried:

This is the code that I have so far...

public IEnumerable<Points> Get(int id)
        {
            _con = new SqlConnection("data source=SQLSERVER1;initial catalog=TRdb01;user id=sa");
            DataTable dt = new DataTable();
            var query = "Select top 1 customer, points from KR.Api_Points where customer = " + id;
            _adapt = new SqlDataAdapter
            {
                SelectCommand = new SqlCommand(query, _con)
            };
            _adapt.Fill(dt);
            //List<Points> pointsbal = new List<Models.Points>(dt.Rows.Count);
            List<Points> pointsbal = new List<Models.Points>(dt.Rows.Count);
     
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow points in dt.Rows)
                {
                    pointsbal.Add(new readPoints(points));
                }
            }

            return pointsbal;
        }


Can someone point me in the right direction please.

Thanks.
Posted
Updated 29-Jul-20 4:46am
Comments
Richard MacCutchan 29-Jul-20 10:35am    
The JSON text is as formatted by the sender, you have no control over that.

1 solution

If your Get(int id) method is the one producing the JSON response, you can probably change the return type from IEnumerable<Points> to Points and then simply return the first result in the dt.Rows collection?

The reason that it's being formatted as an array with square brackets [] is because an enumerable object being serialized to JSON is a collection and will use the square brackets as such. The standard {} indicates an object, so returning an object in the response will serialize it as such.
 
Share this answer
 
v2
Comments
Bullgill Coder 29-Jul-20 10:59am    
Thanks that worked!

start of my code now reads...

public Points Get(int id)

and I've changed the last line to ...

return pointsbal.FirstOrDefault();

Maybe not the cleanest solution, but it works for me!
BillWoodruff 30-Jul-20 0:29am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900