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
The Issue is that offer is not a public Property. The class should look like this:
just fix the class offer property by adding a getter
offer
is a field and by default fields are not serialized by the System.Text.Json serialiser.You can:
offer
a property:public Dictionary<string, long> Offer { get; } = new ...