How to use System.Text.Json to parse Json data on different conditions.

  • Thread starter Thread starter zydjohn
  • Start date Start date
Z

zydjohn

Guest
Hello:
I have to parse some Json data on different conditions. In some cases, Json string is like this:
{"canceled": true, "id": false, "amount": 0}, in this case, the "id" value is bool, here it is false; but in other
cases, the Json string is like this:
{"canceled": false, "id": "123", "amount": 1.0}. In this case, when "canceled" is false, "id" has string value, or actually contains some numeric values.
I am using .NET Core 3.0, so I want to use built-in System.Text.Json to parse the Json string in different cases.
But if I use C# class to define the later case, in which "canceled" is false, then when the Json string I received is the former case, I got the following error message:
{"Cannot get the value of a token type 'False' as a string."}
The following is my code:

public class RootObject
{
[JsonPropertyName("canceled")]
public bool Canceled { get; set; }
#nullable enable
[JsonPropertyName("id")]
public string? ID { get; set; }
[JsonPropertyName("amount")]
public decimal? Amount { get; set; }
#nullable disable
}

string json_data1 = @"{""canceled"": false, ""id"": "123", ""amount"": 1.0}";
RootObject data1 = JsonSerializer.Deserialize<RootObject>(json_data1);
string json_data0 = @"{""canceled"": true, ""id"": false, ""amount"": 0}";
RootObject data0 = JsonSerializer.Deserialize<RootObject>(json_data0);


I think I may have to define two C# classes for each case, but it seem not a good solution.
I think a better solution seems to define one C# class for the both cases, but I can't figure out how to do this.
Please advice. I am using Visual Studio 2019 Version 16.3.2 on Windows 10 (1903) targeting .NET core 3.0.
Thanks,

Continue reading...
 
Back
Top