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 8991261
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T22:41:06+00:00 2026-06-15T22:41:06+00:00

I’m trying to implement the C# aspect of a LightWeight JSON Spec JsonR ,

  • 0

I’m trying to implement the C# aspect of a LightWeight JSON Spec JsonR, but cannot get my head around any kind of recursion :-/ If anyone could help out here it would be more than greatly appreciated.

// Mockup class
public class User {
    public string Name { get; set; }    
    public int Age     { get; set; }
    public List<string> Photos  { get; set; }
    public List<Friend> Friends { get; set; }       
}

// Mockup class
public class Friend {
    public string FirstName { get; set; }
    public string LastName  { get; set; }
}

// Initialize objects
var userList = new List<User>();
userList.Add(new User() { 
    Name   = "Robert",
    Age     = 32,
    Photos  = new List<string> { "1.jpg", "2.jpg" },
    Friends = new List<Friend>() {
        new Friend() { FirstName = "Bob", LastName = "Hope"},
        new Friend() { FirstName = "Mr" , LastName = "T"}
    }
}); 
userList.Add(new User() { 
    Name   = "Jane",
    Age     = 21,
    Photos  = new List<string> { "4.jpg", "5.jpg" },
    Friends = new List<Friend>() {
        new Friend() { FirstName = "Foo"  , LastName = "Bar"},
        new Friend() { FirstName = "Lady" , LastName = "Gaga"}
    }
});

The idea behind it all is to now take the above object and split it into 2 separate collections, one containing the keys, and the other containing the values. Like this we can eventually only send the values over the wire thus saving lots of bandwidth, and then recombine it on the client (a js implementation for recombining exists already)

If all went well we should be able to get this out of the above object

var keys   = new object[] {
    "Name", "Age", "Photos",
    new { Friends = new [] {"FirstName", "LastName"}}};
var values = new [] {
    new object[] {"Robert", 32, new [] {"1.jpg", "2.jpg"},
                                new [] { new [] {"Bob", "Hope"},
                                         new [] {"Mr", "T"}}},
    new object[] {"Jane", 21, new [] {"4.jpg", "5.jpg"},
                              new [] { new [] {"Foo", "Bar"},
                                       new [] {"Lady", "Gaga"}}}};

As a verification we can test the conformity of the result with

Newtonsoft.Json.JsonConvert.SerializeObject(keys).Dump("keys");
// Generates:
// ["Name","Age","Photos",{"Friends":["FirstName","LastName"]}]

Newtonsoft.Json.JsonConvert.SerializeObject(values).Dump("values");
// Generates:
// [["Robert",32,["1.jpg","2.jpg"],[["Bob","Hope"],["Mr","T"]]],["Jane",21,["4.jpg","5.jpg"],[["Foo","Bar"],["Lady","Gaga"]]]]

A shortcut i explored was to take advantage of Newton’s JArray/JObject facilities like this

var JResult = Newtonsoft.Json.JsonConvert.DeserializeObject(
    Newtonsoft.Json.JsonConvert.SerializeObject(userList));

Like this we end up with a sort of array object that we can already start iterating on

Anyone think they can crack this in a memory/speed efficient way ?

  • 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-15T22:41:07+00:00Added an answer on June 15, 2026 at 10:41 pm

    I have a solution that works with your example data. It is not a universal solution and may fail with other examples, but it shows how to use recursions. I did not include any error handling. A real-world solution would have to.

    I use this helper method which gets the item type of the generic lists:

    private static Type GetListItemType(Type listType)
    {
        Type itemType = null;
        foreach (Type interfaceType in listType.GetInterfaces()) {
            if (interfaceType.IsGenericType &&
                interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) {
                itemType = interfaceType.GetGenericArguments()[0];
                break;
            }
        }
        return itemType;
    }
    

    Now, the recursion:

    public void SplitKeyValues(IList source, List<object> keys, List<object> values)
    {
        Type itemType = GetListItemType(source.GetType());
        PropertyInfo[] properties = itemType.GetProperties();
        for (int i = 0; i < source.Count; i++) {
            object item = source[i];
            var itemValues = new List<object>();
            values.Add(itemValues);
            foreach (PropertyInfo prop in properties) {
                if (typeof(IList).IsAssignableFrom(prop.PropertyType) &&
                    prop.PropertyType.IsGenericType) {
                    // We have a List<T> or array
    
                    Type genericArgType = GetListItemType(prop.PropertyType);
                    if (genericArgType.IsValueType || genericArgType == typeof(string)) {
                        // We have a list or array of a simple type
                        if (i == 0)
                            keys.Add(prop.Name);
                        List<object> subValues = new List<object>();
                        itemValues.Add(subValues);
                        subValues.AddRange(
                            Enumerable.Cast<object>(
                                (IEnumerable)prop.GetValue(item, null)));
                    } else {
                        // We have a list or array of a complex type
                        List<object> subKeys = new List<object>();
                        if (i == 0)
                            keys.Add(subKeys);
                        List<object> subValues = new List<object>();
                        itemValues.Add(subValues);
                        SplitKeyValues(
                            (IList)prop.GetValue(item, null), subKeys, subValues);
                    }
                } else if (prop.PropertyType.IsValueType ||
                           prop.PropertyType == typeof(string)) {
                    // We have a simple type
                    if (i == 0)
                        keys.Add(prop.Name);
                    itemValues.Add(prop.GetValue(item, null));
                } else {
                    // We have a complex type.
                    // Does not occur in your example
                }
            }
        }
    }
    

    I call it like this:

    List<User> userList = InitializeObjects();
    List<object> keys = new List<object>();
    List<object> values = new List<object>();
    SplitKeyValues(userList, keys, values);
    

    InitializeObjects initializes the user list as you did above.


    UPDATE

    The problem is that you are using an anonymous type new { Friends = ... }. You would have to create an anonymous type dynamically by using reflection. And that’s pretty nasty. The article “Extend Anonymous Types using Reflection.Emit” seems to do it. (I didn’t test it).

    Maybe an easier approach would do the job. I suggest creating a helper class for the description of class types.

    public class Class
    {
        public string Name { get; set; }
        public List<object> Structure { get; set; }
    }
    

    Now let’s replace an else case in the code above:

    ...
    } else {
        // We have a list or array of a complex type
        List<object> subKeys = new List<object>();
        var classDescr = new Class { Name = genericArgType.Name, Structure = subKeys };
        if (i == 0)
            keys.Add(classDescr);
        List<object> subValues = new List<object>();
        itemValues.Add(subValues);
        SplitKeyValues(
            (IList)prop.GetValue(item, null), subKeys, subValues);
    }
    ...
    

    The result is:
    enter image description here

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Seemingly simple, but I cannot find anything relevant on the web. What is the
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want to count how many characters a certain string has in PHP, but
I am trying to render a haml file in a javascript response like so:
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this

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.