Skip to content

Dictionary<string, object> from Newtonsoft in NetJSON #196

@hhblaze

Description

@hhblaze

First this question was published in a wrong repo ...somehow...

Hi, Is it possible to achieve the same output with NetJSON as by Newtonsoft JSON with Dictionary<string, object> serialization?

 var data = new
    {
        Id = 100,
        Title = "Virsraksts",
        Dict = new Dictionary<string, string>()
        {
            {"one", "first"},
            {"two", "second"},
        },
        DictObj = new Dictionary<string, object>()
        {
            {"eight", 8},
            {"nine", "ninth"},
            {"ten", new List<int> {11, 12, 13}},
            {"eleven", new Dictionary<string, int> {{"more1", 11}, {"more2", 12}}},
        }, // <--------------------- !!!!!!!!!!!   skipped by NetJSON
        Obj = new {o1 = 1, o2 = "divi"},
        Lst = new List<int> {11, 12, 13},
        Lst2 = new List<object> {21, "twenty two"},
        To = subdata,
    };

//--
Newton:

{"Id":100,"Title":"Virsraksts","Dict":{"one":"first","two":"second"},"DictObj":{"eight":8,"nine":"ninth","ten":[11,12,13],"eleven":{"more1":11,"more2":12}},"Obj":{"o1":1,"o2":"divi"},"Lst":[11,12,13],"Lst2":[21,"twenty two"],"To":[{"Id":3,"Title":"Three"},{"Id":4,"Title":"Four"}]}

NetJSON:

{"Id":100,"Title":"Virsraksts","Dict":{"one":"first","two":"second"},"Obj":{"o1":1,"o2":"divi"},"Lst":[11,12,13],"Lst2":[21,"twenty two"],"To":[,]}

It could be possible to replace Dictionary<string,object> with anonymous function, like

 var data1 = new
            {
                Id = 100,
                Title = "Virsraksts",
                Dict = new Dictionary<string, string>()
        {
            {"one", "first"},
            {"two", "second"},
        },
                DictObj = new
                {
                    eight = 8,
                    nine = "ninth",
                    ten = new List<int> { 11, 12, 13 },
                    eleven = new Dictionary<string, int> { { "more1", 11 }, { "more2", 12 } },
                    newProp = 1                   
                },
                Obj = new { o1 = 1, o2 = "divi" },
                Lst = new List<int> { 11, 12, 13 },
                Lst2 = new List<object> { 21, "twenty two" }
            };

but !!sometimes!! the JSON, which need to be sent to the client-side needs properties based on conditions (especially, when there are lots of specific switches and settings and no sense to create static class):

var dict = new Dictionary<string, object>();
if (needTros)
    dict["tros"] = new List<Tro>();
if (needUsers)
    dict["users"] = new Dictionary<long, User>();

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions