Converting an object to json in specified format-contd

偶尔善良 提交于 2019-12-25 02:26:51

问题


This question is a continuation of this.., rather than changing it, I'm asking a new one here.. My required json format is

{
    "nodes": {
        "1": {
            "2": {
                "attriba": "a2",
                "label": "2",
                "attribc": false
            },
            "3": {
                "attriba": "a3",
                "label": "3",
                "attribc": false
            }
        },
        "6": {
            "4": {
                "attriba": "none",
                "label": "4",
                "attribc": false
            },
            "5": {
                "attriba": "none",
                "label": "5",
                "attribc": false
            }
        }
    }
}

Now normally I would create classes and fill them with data and call "Newtonsoft.Json.JsonConvert.SerializeObject" to get the desired json string.

But in this case the format is such that I'm unable to figure out the class structure..

The top class as per my last question would be like the following..

public class Response
    {
        [JsonProperty("nodes")]
        public Dictionary<string, Node> Nodes { get; set; }

     }

The bottom class ..

public class Nodedata
    {

        [JsonProperty("attriba")]
        public string Attriba { get; set; }

        [JsonProperty("attribb")]
        public string Attribb { get; set; }

        [JsonProperty("label")]
        public string Label { get; set; }

        [JsonProperty("attribc")]
        public bool Attribc { get; set; }
    }

But, how do i manage the node class( values "1" & "6") which has again no key value and has a list of Nodedata objects..

Any help will be sincerely appreciated..

Thanks


回答1:


The class for nodes, 1 and 6 will be of type Dictionary<string, Object>

and your class for 2,3,4 and 5 will be as you designed it.

You shoudl get something like

BottomNode node1 = new BottomNode("a2", 2, false);
BottomNode node2 = new BottomNode("a3", 3, false);
BottomNode node3 = new BottomNode("none", 4, false);
BottomNode node4 = new BottomNode("none", 5, false);

Dictionary<string, Object> dic1 = new Dictionary<string, Object>();
Dictionary<string, Object> dic6 = new Dictionary<string, Object>();

dic1.Add("2", node1);
dic1.Add("3", node2);
dic6.Add("4", node3);
dic6.Add("5", node4);

Dictionary<string, Object> nodes = new Dictionary<string, Object>();

nodes.Add("1", dic1);
nodes.Add("6", dic6);


来源:https://stackoverflow.com/questions/25183061/converting-an-object-to-json-in-specified-format-contd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!