Home > Mobile >  How can I easily create readable JSON objects in C# .Net Core similar to JavaScript
How can I easily create readable JSON objects in C# .Net Core similar to JavaScript

Time:06-19

In JavaScript I can easily create an object and assign variables with some very basic notation such as:

const Object = JSON.parse('
  {
    "something": outsideVariable,
    "someArray": [
      "hey",
      "there"
    ]
  }
');

Is there a simple way to do this with C# that is clean and easy to assign variables too? I experimented a bit with the JsonObject but the code for that looks needlessly messy, for example:

JsonObject jsonPayload = new JsonObject
    {
        ["documentId"] = documentID,
        ["testMode"] = true,
        ["signers"] = new JsonArray
        {
            new JsonObject
            {
                ["label"] = "John Smith",
                ["contactMethod"] = new JsonArray
                {
                    new JsonObject
                    {
                        ["type"] = "link"
                    }
                }
            }
        }
    };

I also tried using the literal symbol (@) with a string, but it ends up injecting carriage returns and linefeeds, and inserting variables winds of being a great deal of concatination.

CodePudding user response:

You can use JsonSerializer like this:

using System.Text.Json;

Foo foo = new() { FirstName = "John", LastName = "Mike" };

var json = JsonSerializer.Serialize<Foo>(foo, new JsonSerializerOptions { WriteIndented = true});
Console.WriteLine(json);

class Foo
{
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
}

You will get this result:

{
  "FirstName": "Gio",
  "LastName": "Mike"
}

CodePudding user response:

IMHO , the most close you want is this

var jsonPayload  = new
    {
        documentId = 1,
        testMode = true,
        signers = new object[]
        {
          new {
             label="John Smith",
            contactMethod= new object[]
            {
              new {
                   type="link"
              }
            }
          }
        }
    };

and code

    
var json= System.Text.Json.JsonSerializer
           .Serialize(jsonPayload,new JsonSerializerOptions { WriteIndented = true }); 

//or if you need
var jsonParsed= JsonDocument.Parse(json);

result

{
  "documentId": 1,
  "testMode": true,
  "signers": [
    {
      "label": "John Smith",
      "contactMethod": [
        {
          "type": "link"
        }
      ]
    }
  ]
}
  • Related