Osy#betaRun it on Osyrin: osyrin.com

Reference / JSON

Anonymous types — new { Name, Age }

var p = new { Name = "Ada", Age = 36 }; · new { o.Name, count } · Json d = new { … };

`new { Name = "Ada", Age = 36 }` is an anonymous type, as in C#: a value whose members you read by name (`p.Age`), in a function, a test, a UI action, a computed and the browser alike. Where a `Json` document is wanted — a `Json` column, parameter or return, a request body — the same object becomes that document.

stable5 examples compiled by CIjsontypescsharp

Summary#

new { … } with no type name is an anonymous type, exactly as in C#. Its members are named where it is written, and read by those names wherever the value goes:

var p = new { Name = "Ada", Age = 36 };
var next = p.Age + 1;                    // 37 — `Age` is an int

The same object is also how a JSON document is written inline: given to a Json column, parameter, local or return, or passed as a request body, it becomes that document (#as-a-document).

Signature#

new { Name = value, Other = value }    // members named where they are written
new { o.Name, count }                  // …or named by what they read: Name = o.Name, count = count

Description#

What is an anonymous object's type?#

A type made from its member names and types, in the order written. Nothing declares it and nothing needs to: two anonymous objects with the same members, in the same order, are the same type — as C# says — so a list of them, a Select that makes them, and a local that holds one all agree.

Each member is the type of its value: Age = 36 is an int, Price = 2.5m a decimal, Tags = tags a List<string>. A member's value may be a scalar, a class or entity value, or a list of either.

Where can I read its members?#

Everywhere it can be written. The same lines compile and give the same answer in a function, a [Test], a UI action and a live var computed — and in a page the action runs in the browser, with no call to the server:

using Osysharp.Ui;

[AllowAnonymous]
[Route("/")]
component Greeting() {
  live var person = new { Name = "Ada", Age = 36 };
  live var line = $"{person.Name} is {person.Age}";        // a computed reads the members
  string shown = "";
  action Next() {
    var p = new { person.Name, Age = person.Age + 1 };       // Name inferred from `person.Name`
    shown = $"{p.Name} turns {p.Age}";                        // runs in the browser
  }
  render {
    Stack() {
      Text(line);
      Text(shown);
      Button("Next year", onPress: Next);
    }
  }
}

It behaves as C#'s does: p.ToString() is { Name = Ada, Age = 36 }, and a.Equals(b) compares member by member.

Can a member's name be left out?#

Yes, when the value already names it: a member access gives its member's name and a bare local or parameter gives its own. new { o.Name, count } is new { Name = o.Name, count = count }. A value with no name of its own — a call, an index, a sum — needs one written (Total = a + b), as C# requires.

How do I turn one into JSON?#

JsonSerializer writes it as C# does — its members in the order written, a list as an array:

string Body(string name, List<int> items) {
  return JsonSerializer.Serialize(new { Name = name, Items = items });   // {"Name":"Ada","Items":[1,2]}
}

That works in a page too: the action above could serialize p in the browser.

When does it become a Json document?#

Wherever a Json value is wanted, an anonymous object is converted to that document — a Json column or member, a Json parameter, local or return, and the body of an Http.* request:

entity Job { [Required, MaxLength(50)] string Name; Json Detail; }

void Record(int attempt, string reason) {
  var detail = new { attempt = attempt, reason = reason };
  var j = new Job { Name = "retry", Detail = detail };         // stored as {"attempt":2,"reason":"…"}
}

Json Describe(string code) {
  return new { code = code, fatal = false };                   // a Json return
}

An element of a List<Json> or a value of a Dictionary<string, Json> is converted the same way, however it gets there — Add, Insert, AddRange, the indexer, a collection initializer or literal, or a whole Select(…).ToList() assigned to a List<Json>. That is how a request body with a list in it is built:

string Messages(List<string> lines) {
  List<Json> messages = [];
  messages.Add(new { role = "system", content = "Be brief." });
  foreach (var line in lines) { messages.Add(new { role = "user", content = line }); }
  return JsonSerializer.Serialize(new { model = "m-1", messages = messages });
  // {"model":"m-1","messages":[{"role":"system","content":"Be brief."},{"role":"user","content":"…"}]}
}

Once it is a Json, it is a document like any other: read it back through JsonSerializer.Deserialize<T>, not by member.

Can one anonymous object hold another?#

Yes — and then the outer object is a document (a Json value), as it always was: new { code = "E17", inner = new { retries = 3 } } writes {"code":"E17","inner":{"retries":3}}, and a list of anonymous objects inside one is an array of documents. Its members are not read by name; write a class when you need to read a nested shape back.

What does the compiler refuse?#

writtenwhy
new { a = 1, a = 2 }a member given twice
new { ["a"] = 1 }the dictionary spelling — a member is a name
new { Total() }a value with no name of its own: write Total = Total()
int runs = new { a = 1 };an anonymous object is not an int

Examples#

A list of anonymous objects, made by a Select and read by member:

int LongNames(List<string> names) {
  var rows = names.Select(n => new { n, Len = n.Length }).ToList();
  return rows.Where(r => r.Len > 3).Count();
}

See also#

  • JsonSerializer — JsonSerializer.Serialize writes an anonymous object as C# does
  • Json — the Json document an anonymous object becomes where one is wanted
  • Http.* — an anonymous object as a request body

Related

JsonSerializer

Turn a value into a JSON string and a JSON string into a typed object — the C#-faithful System.Text.Json spelling…

Json

A member that holds a JSON document — an object, an array, or any value. It is stored as real jsonb, and written and…

Http.*

Make an outbound HTTP call to a URL you build at runtime — a webhook, a third-party API, a discovered endpoint…