mardi 22 janvier 2019

C# deserialize to either list or string

Very close to How to define variable in class to receive either List<string> or string when deserializing JSON?

I prefer to use python to parse json. Didn't test this but sure it works, done this few times now. #PythonForLife

import json
str = '{
        "Resource" : ["1", "2"]
       }'
j = json.loads(str)
if ( isinstance( str["Resource"], list ):
        print(str["Resource"][0]) //or do whatever
else:
        print(str["Resource"])    //same

I wonder what the best practice is to do something like this in C#. I have a model like

public class RootObject 
{
    public IEnumerable<string> Resource {get; set;)
}

And this is so fragile because it's hard-coded to handle collections only and breaks once a string is received. I hate to try catch and use another model because this is just one property, I do have much more like this in the same model. Why is this even a problem? Is the best/better/working solution what I linked here?

Aucun commentaire:

Enregistrer un commentaire