12

i want to create an anonymous class in vb.net exactly like this:

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.

2
  • 1
    Your example shows an anonymous class in C#, it is not related to json.. Commented May 11, 2009 at 20:13
  • The context behind his question can be found in more detail here: haacked.com/archive/2009/04/14/… Commented May 13, 2009 at 17:01

2 Answers 2

18

VB.NET 2008 does not have the new[] construct, but VB.NET 2010 does. You cannot create an array of anonymous types directly in VB.NET 2008. The trick is to declare a function like this:

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

And have the compiler infer the type for us (since it's anonymous type, we cannot specify the name). Then use it like:

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. This is not called JSON. It's called an anonymous type.

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

4 Comments

I think this is no longer true.
It's still true with VS2008 ;-)
Make sure when you talk about this, that you disclaimer the Compiler Options for VB. Some might read this and have their options set to only allow well defined references (ie Option Strict On, Option Infer Off, and Option Explicit On)
You can turn Option Explicit On and Option Infer Off or Option Strict On per file (I suggest using a partial class in a new file in this case). C# uses the keyword dynamic to do this across multiple files. Or generics will infer the correct anonymous type if you instead had say a function which returns a List(Of T).
8

In 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?"}}
  }
}

Comments

Your Answer

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