Home > Software design >  Deserializing a data member that could be int or string c#
Deserializing a data member that could be int or string c#

Time:09-13

I've created an API endpoint that is receiving a List of objects. The 'AttributeValue' of the objects could be either a string or an int. Here is a generic version of my code:

public class b
{
  public List<a> myList {get; set;} = new List<a>();
}

public class a
{
   public object AttributeValue {get; set;}
}

The problem is, I need to know the original data type. When I check the type it tells me "System.Text.Json.JsonElement". I also tried something like the following:

if(b.myList[0].AttributeValue is int) { do something.. }
else if(b.myList[0].AttributeValue is string) {do something...}
else {throw error}

I always throw an error so I assume I am losing my original data type when I am deserializing. Any ideas what I can do?

CodePudding user response:

try to cast to JsonElement

var json="{\"myList\":[{\"AttributeValue\":1},{\"AttributeValue\":\"2\"},{\"AttributeValue\":3},{\"AttributeValue\":\"4\"}]}";

var b =System.Text.Json.JsonSerializer.Deserialize<b>(json);

if (((JsonElement) b.myList[0].AttributeValue).ValueKind.ToString()=="Number") ...
else
 if (((JsonElement) b.myList[1].AttributeValue).ValueKind.ToString()=="String")... 

CodePudding user response:

you can use Oneof<> nuget.

 OneOf<string, int> result = funcHere(b.myList);
            return result.Match<xxx>(
                stringValue =>
                {
                  // do some string procedure
                },
                intValue =>
                {
                  // do some int procedure
                };

  • Related