-1

I am Trying to serialise an ojekt to json but it givs me alway an emty json obiject bak I am usning the default build in serialiser.

My Object to seriaclise:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json.Serialization;

[Serializable]
public class Order
{
    [JsonPropertyName("contractornumber")]
    public readonly uint contractorNumber;
    [JsonPropertyName("contractorname")]
    public readonly string contractorName;
    [JsonPropertyName("durationofcontract")]
    public readonly TimeSpan durationOfContract;
    [JsonPropertyName("ordernumber")]
    public readonly uint orderNumber;
    [JsonPropertyName("iban")]
    public readonly string IBAN;
    public Order( uint contractorNumber, string contractorName,TimeSpan durationOfContract, uint orderNumber,string IBAN)
    {

        this.contractorNumber = contractorNumber;
        this.contractorName = contractorName;
        //this.durationOfContract = durationOfContract;   
        this.orderNumber = orderNumber;
        this.IBAN = IBAN;

    }

    public Order() { }
}

And I try to serialise it So:

var order = new Order(89745, "F", DateTime.Now.TimeOfDay, 84537, "FU");

var k = JsonSerializer.Serialize(order);
Console.WriteLine(k);

And It gives me an output : "{}"

I am using .net 6 C# on winodws 10.

KRIShark
  • 17
  • 5

2 Answers2

2

If you want to include field and even readonly fields with System.Text.Json, you can specify a JsonSerializerOptions object to use:

JsonSerializerOptions jsonSerializerOptions = new()
{
    IncludeFields = true,
    IgnoreReadOnlyFields = false
}

Then use it like this:

var k = JsonSerializer.Serialize(order, jsonSerializerOptions);

Now the readonly fields should be serialized and deserialized.

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
0

You have to set an option like this to include fields:

var order = new Order(89745, "F", DateTime.Now.TimeOfDay, 84537, "FU");
var options = new JsonSerializerOptions { IncludeFields = true };
var k = JsonSerializer.Serialize<Order>(order, options);
n-azad
  • 69
  • 5