-1

I would like to deserialize a JSON string which contains multiple object types. So for instance here are my two POCO classes:

public class Car 
{
  [Key]
  public int Id { get; set; }
  public string Color { get; set; }
}

public class Driver
{
  [Key]
  public int Id { get; set; }
  public string Firstname { get; set; }
}

Now I would like to have a JSON string which would have an array of objects from both classes (which are unrelated) and that would get deserialized into their respective POCO classes using the Newtonsoft json package in Visual Studio.

Is this possible and if so, what does the JSON format look like? An example would be appreciated with just 2 objects per class to show the array of objects and the two class types coexisting within a single JSON string which is passed to something like JsonConvert.DeserializeObject.

EDIT: the JSON for these classes and an object within would individually look something like:

for Car...

[
{
  "color": "red"
},
{
  "color": "blue"
}
]

and for Driver...

[
{
  "Firstname": "Fred"
},
{
  "Firstname": "Sally"
}
]

But now could those be combined into one string, but with some sort of extra parm to define to which CLASS each set belongs such as:

"Car"
[
{
  "color": "red"
},
{
  "color": "blue"
}
],
"Driver"
[
{
  "Firstname": "Fred"
},
{
  "Firstname": "Sally"
}
]

See how this has 2 unrelated classes in a single JSON string? Now I'd like to do a single (if possible) Jsonconvert into the respective classes so that "Car" winds up with 2 objects and "Driver" winds up with 2 (for this example).

Donna
  • 343
  • 1
  • 2
  • 13
  • There are already several questions about this including [How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?](https://stackoverflow.com/q/8030538/3744182), [Deserializing polymorphic json classes without type information using json.net](https://stackoverflow.com/q/19307752/3744182), [Json.net serialize/deserialize derived types?](https://stackoverflow.com/q/8513042/3744182) and [how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET](https://stackoverflow.com/q/6348215/3744182). Do any of those meet you needs? – dbc Apr 20 '19 at 17:11
  • How do you distinguish between the two classes? Both have only an int and a string property? From the point of JSON they look the same. Unless you have an array or some kind of enum that limits Color to a predetermined list of colors I don't see how JSONConvert can tell the difference between two classes that both only have an int and a string. – Sean Apr 20 '19 at 17:47
  • They're just two very simple classes for example purposes. I figure the class NAME distinguishes them? They're unrelated and can have many/different properties. Man how does one line-break in these comments!? I checked and didn't find anything matching, just several similar keywords. I just want to be able to combine multiple objects from different classes into a single JSON string for deserialization. Wonder if that's possible with Newtonsoft? – Donna Apr 20 '19 at 19:59

1 Answers1

0

Could be done like this:

using System.Collections;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var objArray = new ArrayList
            {
                new Car {Id = 1, Color = "blue"},
                new Driver {Id = 1, Firstname = "John"},
                new Car {Id = 2, Color = "blue"},
                new Driver {Id = 2, Firstname = "Jane"}
            };
            var json = JsonConvert.SerializeObject(objArray);

            var jArray = JArray.Parse(json);

            foreach (var child in jArray.Children())
            {
                if (child.Children().Any(token => token.Path.Contains("Color")))
                {
                    // we got a Car
                    var car = ((JObject) child).ToObject<Car>();
                }
                else if (child.Children().Any(token => token.Path.Contains("Firstname")))
                {
                    // we got a Driver
                    var driver = ((JObject) child).ToObject<Driver>();
                }
            }
        }
    }

    public class Car
    {
        public int Id { get; set; }
        public string Color { get; set; }
    }

    public class Driver
    {
        public int Id { get; set; }
        public string Firstname { get; set; }
    }
}
xcskilab
  • 189
  • 1
  • 9
  • Thanks for your response. Let me clarify... is there a JSON string format which would allow having multiple classes within it, which are exclusive of each other and that would feed into the POCO classes as objects when deserialized? What would the JSON look like in that case? – Donna Apr 20 '19 at 20:17
  • 1
    Take a look here: https://skrift.io/articles/archive/bulletproof-interface-deserialization-in-jsonnet/ – xcskilab Apr 20 '19 at 22:53
  • Thank you. That makes a lot of sense. I wound up setting start & end point markers in my JSON and then parsing out the blocks of the different classes (each containing 1+ objects) before I then passed to the json.net to deserialize each block. – Donna Apr 25 '19 at 17:59