Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8619259
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T06:17:56+00:00 2026-06-12T06:17:56+00:00

I have a JSON-array containing objects of different types with different properties. One of

  • 0

I have a JSON-array containing objects of different types with different properties. One of the properties is called “type” and determines the type of the array item. Here is an example of my data:

   [{
        type : "comment",
        text : "xxxx"
    }, {
        type : "code",
        tokens : [{
                type : "ref",
                data : "m"
            }, {
                type : "operator",
                data : "e"
            }
        ]
    }, {
        type : "for",
        boundLocal : {
            type : "local",
            name : "i",
            kind : "Number"
        },
        upperBound : {
            type : "ref",
            tokens : [{
                    type : "operator",
                    data : "3"
                }, {
                    type : "operator",
                    data : "0"
                }
            ]
        },
        body : [{
                type : "code",
                tokens : [{
                        type : "ref",
                        data : "x"
                    }
                ]
            }, {
                type : "code",
                tokens : [{
                        type : "ref",
                        data : "y"
                    }
                }
                ]
        ]
    ]

To map those objects to my .Net implementation I define a set of classes: one base class and several child classes (with a complex hierarchy, having 4 “generations”). Here is just a small example of these classes:

public abstract class TExpression
{
    [JsonProperty("type")]
    public string Type { get; set; }
}

public class TComment : TExpression
{
    [JsonProperty("text")]
    public string Text { get; set; }
}   

public class TTokenSequence : TExpression
{
    [JsonProperty("tokens")]
    public List<TToken> Tokens { get; set; }
}

What I want to reach is to be able to deserialize this array into a covariant generic list, declared as:

List<TExpression> myexpressions = JsonConvert.DeserializeObject<List<TExpression>>(aststring);

This list should contain the instances of appropriate child classes inheriting from TExpression, so I can use the following code later in my code:

foreach(TExpression t in myexpressions)
{
    if (t is TComment) dosomething;
    if (t is TTokenSequence) dosomethingelse;
}

How can I reach it using JSON.NET?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-12T06:17:57+00:00Added an answer on June 12, 2026 at 6:17 am

    Here is an example using CustomCreationConverter.

    public class JsonItemConverter :  Newtonsoft.Json.Converters.CustomCreationConverter<Item>
    {
        public override Item Create(Type objectType)
        {
            throw new NotImplementedException();
        }
    
        public Item Create(Type objectType, JObject jObject)
        {
            var type = (string)jObject.Property("valueType");
            switch (type)
            {
                case "int":
                    return new IntItem();
                case "string":
                    return new StringItem();
            }
    
            throw new ApplicationException(String.Format("The given vehicle type {0} is not supported!", type));
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // Load JObject from stream
            JObject jObject = JObject.Load(reader);
    
            // Create target object based on JObject
            var target = Create(objectType, jObject);
    
            // Populate the object properties
            serializer.Populate(jObject.CreateReader(), target);
    
            return target;
        }
    }
    
    public abstract class Item
    {
        public string ValueType { get; set; }
    
        [JsonProperty("valueTypeId")]
        public int ValueTypeId { get; set; }
    
        [JsonProperty("name")]
        public string Name { get; set; }
    
        public new virtual string ToString() { return "Base object, we dont' want base created ValueType=" + this.ValueType + "; " + "name: " + Name; }
    }
    
    public class StringItem : Item
    {
        [JsonProperty("value")]
        public string Value { get; set; }
    
        [JsonProperty("numberChars")]
        public int NumberCharacters { get; set; }
    
        public override string ToString() { return "StringItem object ValueType=" + this.ValueType + ", Value=" + this.Value + "; " + "Num Chars= " + NumberCharacters; }
    
    }
    
    public class IntItem : Item
    {
        [JsonProperty("value")]
        public int Value { get; set; }
    
        public override string ToString() { return "IntItem object ValueType=" + this.ValueType + ", Value=" + this.Value; }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            // json string
            var json = "[{\"value\":5,\"valueType\":\"int\",\"valueTypeId\":1,\"name\":\"numberOfDups\"},{\"value\":\"some thing\",\"valueType\":\"string\",\"valueTypeId\":1,\"name\":\"a\",\"numberChars\":11},{\"value\":2,\"valueType\":\"int\",\"valueTypeId\":2,\"name\":\"b\"}]";
    
            // The above is deserialized into a list of Items, instead of a hetrogenous list of
            // IntItem and StringItem
            var result = JsonConvert.DeserializeObject<List<Item>>(json, new JsonItemConverter());
    
            foreach (var r in result)
            {
                // r is an instance of Item not StringItem or IntItem
                Console.WriteLine("got " + r.ToString());
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have several string each containing a JSON representation of an array of objects.
My problem: I have an JSON Array containing arrays, which i render into the
I have a single array json string containing data: [{Name:John,Age:22}, {Name:Jack,Age:56}, {Name:John,Age:82}, {Name:Jack,Age:95}] I
I have two files, one containing an array in PHP that is echo ed
I have a JSON array like this: { forum:[ { id:1, created:2010-03-19 , updated:2010-03-19
I have a JSON array like below: var jsonArray = [{k1:v1},{k2:v2},{k3:v3},{k4:v4},{k5:v5}] I don't know
I have something like a json array output, it comes like : { data:
I have a two dimensional JSON array where each element contains several attributes. The
i have this JSON: var projects_array = new Array( {name:myName1, id:myid1, index:1}, {name:myName2, id:myid2,
I have some troubles mapping a JSON Array to RestKit. This is what the

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.