-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.

2
  • I think they need to properties, not fields. Commented Nov 10, 2022 at 14:52
  • Well, it is possible to serialize fields ... There is a duplicated question about this topic Commented Nov 10, 2022 at 14:57

2 Answers 2

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.

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.