# Creating Strongly Typed JSON Collections

Sometimes, it might be useful to declare JSON and a corresponding code-behind that makes it possible to programmatically create collections that, when serialized to JSON, become documents that are collections of other JSON objects.

In this example, it's described how to create a strongly typed collection of `Person` objects as created here:

```javascript
{
  "Name": ""
}
```

```csharp
using Starcounter;

namespace TypedJSONCollectionSample 
{
    partial class Person : Json 
    {
    }
}
```

To start creating a collection, add a new item using the `Starcounter Typed JSON with code-behind` template. In this example, it'll be named "PersonCollection".

To allow this JSON to contain a collection of other objects, the JSON-by-example has to look something like this:

```javascript
{
  "People": [{}]
}
```

In the code-behind for the JSON object, make the collection strongly typed by using the following code:

```csharp
using Starcounter;

namespace TypedJSONCollectionSample 
{
    partial class PersonCollection : Json 
    {
      static PersonCollection() 
      {
        DefaultTemplate.People.ElementType.InstanceType = typeof(Person);
      }
    }
}
```

With this setup, it's possible to add instances of the `Person` class to the `PersonCollection`:

```csharp
static void Main() 
{
  var alice = new Person() { Name = "Alice" };
  var bob = new Person() { Name = "Bob" };

  var friends = new PersonCollection();
  friends.People.Add(alice);
  friends.People.Add(bob);

  Console.WriteLine(alice.ToJson()); // {"Name":"Alice"}
  Console.WriteLine(bob.ToJson()); // {"Name":"Bob"}
  Console.WriteLine(friends.ToJson()); // {"People":[{"Name":"Alice"},{"Name":"Bob"}]}
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.starcounter.io/2.3.1/cookbook/creating-strongly-typed-json-collections.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
