I want to construct Json.NET object using object initializers for collections.
I can do:
JObject jsonObject = new JObject { { "Date", DateTime.Now }, { "obj", new JObject { { "string", "bla" } } } };
Now I want to do for example:
var j=new HashSet<int> { 5 };
JObject jsonObject = new JObject { { "hashset", j } };
But I get an error because there is no implicit conversion from HashSet to JToken
This works:
var j=new HashSet<int> { 5 };
JObject jsonObject = new JObject { { "hashset", JToken.FromObject(j) } };
but gets very verbose for complex construction.
Unfortunately I can't use extension methods to add an implicit conversion from HashSet to JToken which would have been probably ideal.
Any other ways to solve this ?
JToken t = JToken.FromObject(new { j = new HashSet<int> { 5 } });ThenJObject jsonObject = new JObject { { "hashset", t } };.