-1

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();
}
dbc
  • 104,963
  • 20
  • 228
  • 340
julian bechtold
  • 1,875
  • 2
  • 19
  • 49
  • Either convert your `offer` field to a property or see [How to use class fields with System.Text.Json.JsonSerializer?](https://stackoverflow.com/q/58139759/3744182). – dbc Jan 28 '23 at 21:04

3 Answers3

1

just fix the class offer property by adding a getter

public Dictionary<string, long> offer { get; } = new Dictionary<string, long>();
Serge
  • 40,935
  • 4
  • 18
  • 45
1

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);
    
tymtam
  • 31,798
  • 8
  • 86
  • 126
0

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;
    }
}
julian bechtold
  • 1,875
  • 2
  • 19
  • 49