I want to generate JSON data from a database table using Web API C#. The following is the table structure
CREATE TABLE [dbo].[Fields](
[fieldID] [varchar](250) NOT NULL,
[displayName] [varchar](500) NOT NULL,
[id] [bigint] NOT NULL,
[tenant] [bigint] NOT NULL,
[Name] [varchar](500) NOT NULL,
[description] [varchar](500) NULL,
[type] [varchar](250) NULL
) ON [PRIMARY]
GO
And having following data
INSERT [dbo].[Fields] ([fieldID], [displayName], [id], [tenant], [Name], [description], [type]) VALUES (N'100', N'Loan#', 18, 3, N'Loan#', N'Loan#', N'string')
GO
INSERT [dbo].[Fields] ([fieldID], [displayName], [id], [tenant], [Name], [description], [type]) VALUES (N'101', N'LoanProgram', 19, 3, N'LoanProgram', N'LoanProgram', N'string')
GO
From this table and I want to generate a JSON in the following format using the Web API
{
"100": {
"fieldID": "100",
"displayName": "Loan#",
"id": 18,
"tenant": 3,
"name": "Loan#",
"description": "Loan#",
"type": "string"
},
"101": {
"fieldID": "101",
"displayName": "LoanProgram",
"id": 19,
"tenant": 3,
"name": "LoanProgram",
"description": "LoanProgram",
"type": "string"
}
}
Following is my API controller
[HttpGet("Fields/{id}/fields/")]
public Object GetFields(int id)
{
return _fieldService.GetFields(id).Result;
}
I have created a class as follows
public class ConfiguredFields
{
public int fieldID { get; set; }
public string displayName { get; set; }
public int id { get; set; }
public string tenant { get; set; }
public string name { get; set; }
public string description { get; set; }
public string type { get; set; }
}
And using Dapper I have called the SP and tried to the value
public async Task<Object> GetWorkflowFields(int WID)
{
using (var db = new SqlConnection(_connectionString.Value))
{
var parameters = new DynamicParameters();
parameters.Add("@pm_ID", WID);
var result = await db.QueryAsync<ConfiguredFields>("SP_GetLoanFields", parameters, commandType: CommandType.StoredProcedure);
return result.ToList();
}
}
But I am getting the JSON in the following format (with array lap and not in the desired format where fieldID wise wrapping is not there.)
[
{
"fieldID": 100,
"displayName": "Loan#",
"id": 18,
"tenant": "3",
"name": "Loan#",
"description": "Loan#",
"type": "string"
},
{
"fieldID": 101,
"displayName": "LoanProgram",
"id": 19,
"tenant": "3",
"name": "LoanProgram",
"description": "LoanProgram",
"type": "string"
}
]
Please suggest what all changes required here to get the JSON in desired format? Please help me to solve this?
Enumerable.ToDictionaryofficial documentation ... there should be an exampleresult, instead ofToList(), you can callToDictionary(). As an argument you will pass a lambda that selects the key (fieldIDin your case). The resulting dictionary should map nicely to the json you presented. learn.microsoft.com/en-us/dotnet/api/…