0

I am currently using this ugly code to add a bunch of key/value pairs (kept in a Dictionairy) to a JObject. It does not add them as children, but as siblings. Well the code works, but it would be cleaner if they were added as child nodes. (the dynamic object e, holds the JObject)

    public void trigger(dynamic e ,Pairs extras)
    {
        if (Post != null)
        {
            foreach (KeyValuePair<string, object> entry in extras)
            {
                Newtonsoft.Json.Linq.JValue val = new Newtonsoft.Json.Linq.JValue(entry.Value);
                e.Add(entry.Key, val);
            }
            Post(this,  e);
        }
    }
Dr.YSG
  • 7,171
  • 22
  • 81
  • 139
  • *Well the code works* - then what is your question, and what problem are you having, please? – dbc Apr 11 '16 at 22:24
  • I don't want it to insert a sibling of the node, but a child. But I had trouble with .AddFirst() – Dr.YSG Apr 11 '16 at 22:26
  • *I don't want it to insert a sibling of the node* - what node, `e`? [`e.Add(string, JToken)`](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Add.htm) adds the specified property as the last child of `e` so I'm not sure I know what you mean. Can you create an [example](https://stackoverflow.com/help/mcve) of the input JSON you have and what you want to get as a result? – dbc Apr 11 '16 at 23:24
  • See my answer below, where I suggest a different way of approaching this. – Dr.YSG Apr 13 '16 at 15:58

1 Answers1

0

For my particular needs, (sending dynamic object via SignalR which uses JSON.NET to serialize). I have found a simpler solution.

My issue was that I had a dymanic sealed class, that JSON.NET was creating a JTOKEN for, and then I was trying to add more data. When I did the e.Add(string, JTOKEN) it was creating a second child tree. That was ugly.

My solution can now be found at:

can one convert a dynamic object to an ExpandoObject (c#)

Community
  • 1
  • 1
Dr.YSG
  • 7,171
  • 22
  • 81
  • 139