2009-05-11 7 views
12

Quiero crear una clase anónima en vb.net exactamente como esta:Anónimo inicialización de clase en VB.Net

var data = new { 
       total = totalPages, 
       page = page, 
       records = totalRecords, 
       rows = new[]{ 
        new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}}, 
        new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}}, 
        new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}} 
       } 
      }; 

THX.

+1

Su ejemplo muestra una clase anónima en C#, que no está relacionado con JSON .. –

+0

El contexto detrás de su pregunta se puede encontrar con más detalle aquí: http: // haacked. com/archive/2009/04/14/using-jquery-grid-with-asp.net-mvc.aspx –

Respuesta

17

VB.NET 2008 no tiene el constructo new[], pero VB.NET 2010 sí lo tiene. No se puede crear una matriz de tipos anónimos directamente en VB.NET 2008. El truco es declarar una función como esta:

Function GetArray(Of T)(ByVal ParamArray values() As T) As T() 
    Return values 
End Function 

Y tienen el compilador inferir el tipo para nosotros (ya que es tipo anónimo, no podemos especificar el nombre). Luego úselo como:

Dim jsonData = New With { _ 
    .total = totalPages, _ 
    .page = page, _ 
    .records = totalRecords, _ 
    .rows = GetArray(_ 
     New With {.id = 1, .cell = GetArray("1", "-7", "Is this a good question?")}, _ 
     New With {.id = 2, .cell = GetArray("2", "15", "Is this a blatant ripoff?")}, _ 
     New With {.id = 3, .cell = GetArray("3", "23", "Why is the sky blue?")} 
    ) _ 
} 

PS. Esto no se llama JSON. Se llama tipo anónimo.

+0

Creo que esto ya no es cierto. –

+0

Consulte http://stackoverflow.com/questions/3799403 – royco

+0

. Sigue siendo cierto con VS2008 ;-) –

8

En VS2010:

Dim jsonData = New With { 
    .total = 1, 
    .page = Page, 
    .records = 3, 
    .rows = { 
    New With {.id = 1, .cell = {"1", "-7", "Is this a good question?"}}, 
    New With {.id = 2, .cell = {"2", "15", "Is this a blatant ripoff?"}}, 
    New With {.id = 3, .cell = {"3", "23", "Why is the sky blue?"}} 
    } 
} 
Cuestiones relacionadas