Home > database >  How to convert "TO JSON AUTO" in a model in c# (SQL Server)
How to convert "TO JSON AUTO" in a model in c# (SQL Server)

Time:01-25

I need your help, I am trying to solve this.

I have a query to get some tables and columns and this is the result:

DECLARE @test2 varchar(max) = (

    SELECT DISTINCT
        ba.TABLE_NAME       AS Tabla,
        detalle.COLUMN_NAME AS Columna

    FROM
        INFORMATION_SCHEMA.COLUMNS AS ba
        LEFT JOIN INFORMATION_SCHEMA.COLUMNS AS detalle ON
            detalle.TABLE_NAME = ba.TABLE_NAME

    WHERE
        ba.TABLE_CATALOG = 'tcGenerales'
        AND
        ba.TABLE_NAME NOT IN ( 'Bitacora', 'Version' )

    FOR JSON AUTO
);

SELECT @test2 AS JsonRes;

Result looks like this JSON:

[
   {
      "Tabla": "CA_Asentamiento",
      "Detalle": [
         { "Columna": "Asentamiento" },
         { "Columna": "CodigoPostal" }
      ]
   },
   {
      "Tabla": "CA_ClaveProductoServicio",
      "Detalle": [
         { "Columna": "Clave" },
         { "Columna": "Descripcion" },
         { "Columna": "FechaAlta" }
      ]
   }
]

In C# how can I convert that JSON into a model class?

I have this class:

public class TablaDTO
{
    public string        Tabla   { get; set; }
    public List<Detalle> Detalle { get; set; }
}

public class Detalle
{
    public string Columna { get; set; }
}

Thanks for your help - I hope you can help me with this.

CodePudding user response:

You can use net naitive System.Text.Json library

using System.Text.Json;

List<TablaDTO> tablaDTO = System.Text.Json.JsonSerializer.Deserialize<List<TablaDTO>>(json);

Or IMHO it is better to install Newtonsoft.Json nuget package and use this code

using Newtonsoft.Json;

 List<TablaDTO> tablaDTO = JsonConvert.DeserializeObject<List<TablaDTO>>(json);
  • Related