1

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?

Gopi
  • 216
  • 1
  • 3
  • 11
  • You can either de-serialize into a `List` or a `string`, one option would be to collect a collection inside a `string` type with a delimiter, which can be readily converted into an array using `Split` api – Mrinal Kamboj Jan 23 '19 at 06:48
  • 1
    Since you are using Json.NET, this looks like a duplicate of [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182) and/or [How to handle json that returns both a string and a string array?](https://stackoverflow.com/q/22052430/3744182). Agree? The solution in the question you linked to is not commonly used since it requires modification of the model instead of application of a `JsonConverter`. – dbc Jan 23 '19 at 07:02
  • I'm for https://stackoverflow.com/a/18997172/3269453, looks standard, and keeps the model less messy. Thank you. – Gopi Jan 23 '19 at 07:18
  • @Gopi yes that looks like a very clean solution – Mrinal Kamboj Jan 23 '19 at 07:23
  • Feels like a lot of people may need to maintain a form of this standard implementation. This should come out of the box. – Gopi Jan 23 '19 at 07:24
  • @Gopi - When working entirely with strongly typed languages (like c#), this sort of problem is unlikely to arise. But it does seem to come up quite often otherwise which is likely why [How to handle both a single item and an array for the same property using JSON.net](https://stackoverflow.com/q/18994685/3744182) has so many views & votes. – dbc Jan 23 '19 at 07:26

1 Answers1

0

You should use Dictionary instead of List for example :

    class MyClass
    {
        public void Test()
        {
            var x = @"{'Resource' : ['1', '2']}";

            var r = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(x);
        }
    }

    public static void Main(string[] args)
    {
        var l = new MyClass();
        l.Test();
    }
Captain
  • 113
  • 2
  • 9