skip to Main Content

I am trying to serialize a simple class:

public class Offer_RPC
{
    /// <summary>
    /// this dictionary contains your requested additions ans substractions, in mojos.<br/>
    /// if you wan to offer an nft for example, use the launcher id such as <br/>
    /// "1": 1000000000000 (offer for 1 xch) <br/>
    /// "cc4138f8debe4fbedf26ccae0f965be19c67a49d525f1416c0749c3c865dxxx", -1 <br/>
    /// </summary>
    public Dictionary<string, long> offer = new Dictionary<string, long>();
    public override string ToString()
    {
        JsonSerializerOptions options = new JsonSerializerOptions();
        options.WriteIndented = false;
        options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
        string jsonString = JsonSerializer.Serialize(this, options: options);
        return jsonString;
    }
}

when calling .ToString(), the resulting json is {}

This is my test method:

[Fact]
public void TestOffer()
{
    Offer_RPC test = new Offer_RPC();
    test.offer.Add("1", 1);
    test.offer.Add("2", -1);
    string json = test.ToString();
}

3

Answers


  1. Chosen as BEST ANSWER

    The Issue is that offer is not a public Property. The class should look like this:

    public class Offer_RPC
    {
        public Offer_RPC()
        {
            offer = new Dictionary<string, long>();
        }
        /// <summary>
        /// this dictionary contains your requested additions ans substractions, in mojos.<br/>
        /// if you wan to offer an nft for example, use the launcher id such as <br/>
        /// "1": 1000000000000 (offer for 1 xch) <br/>
        /// "cc4138f8debe4fbedf26ccae0f965be19c67a49d525f1416c0749c3c865dxxx", -1 <br/>
        /// </summary>
        public Dictionary<string, long> offer { get; set; }
        public override string ToString()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();
            options.WriteIndented = false;
            options.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;
            string jsonString = JsonSerializer.Serialize(this, options: options);
            return jsonString;
        }
    }
    

  2. just fix the class offer property by adding a getter

    public Dictionary<string, long> offer { get; } = new Dictionary<string, long>();
    
    Login or Signup to reply.
  3. offer is a field and by default fields are not serialized by the System.Text.Json serialiser.

    You can:

    1. Make offer a property:
      public Dictionary<string, long> Offer { get; } = new ...
    2. Include fields:
      var options = new JsonSerializerOptions
      {
           IncludeFields = true,
      };
      var json = JsonSerializer.Serialize(o, options);
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search