Search code examples
c#jsonpoco

C#: How do you build semi-structured objects analogous to JSON?


I want to iterate through a 2D Array contents[,], and build up a JSON-like object as a do so. The structure is like below. This will then be sent to a server endpoint, processed by a server-side function and stored into a database.

In JavaScript this would have been straightforward, but that is because typing is dynamic. As far as I can tell, I have two options for building up sem-structured data in C#:

  1. Create a model as mentioned here: Convert C# Object to Json Object and then convert to JSON
  2. Build up a nested hashtable (not dictionary because I won't know types of the values until I need to build the object)

What is the normal way of doing this in C#? I have also come across the term 'POCO', which seems to somewhat correspond to point 1.?

[
    {
        tableName: someName,
        fields: [ordered, list, of, field, names],
        values: [
            [ordered, list, of, cell, row, values],
            [ordered, list, of, cell, row, values],
            [ordered, list, of, cell, row, values]
        ]
    },
    {
        tableName: someName,
        fields: [ordered, list, of, field, names],
        values: [
            [ordered, list, of, cell, row, values],
            [ordered, list, of, cell, row, values],
            [ordered, list, of, cell, row, values]
        ]
    },
    etc
]

Solution

  • It seems that your structure is rigid and that only the data values are different, in this case you should just use an object type for your values. Your class could then look something like this;

    class MyObject
    {
        String Tablename;
        List<Field> myFields = new List<Field>();
        List<object> values = new List<object>();
    }
    

    Or you could just create a Json Object directly and parse that if you need to retrieve any additional data.