0

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 ?

4
  • This feels like a XY Problem - meta.stackexchange.com/questions/66377/what-is-the-xy-problem . Take a step back and explain to us your underlying problem. What are you trying to achieve? Commented Jun 25, 2018 at 0:39
  • no it's not an XY problem, why not read the question instead of throwing this back Commented Jun 25, 2018 at 0:42
  • This is a little over my head so I'm not sure if this is any better, but what if you 'tokenized' when you create the HashSet? JToken t = JToken.FromObject(new { j = new HashSet<int> { 5 } }); Then JObject jsonObject = new JObject { { "hashset", t } };. Commented Jun 25, 2018 at 1:39
  • thx, I already have that above, the whole point of this question is to try to allow the very concise syntax Commented Jun 25, 2018 at 2:06

1 Answer 1

2

Actually you are utilizing the collection initializers, since JObject implements IEnumerable and has Add method with the following signature:

public void Add(string propertyName, JToken value)

So all you need is to create Add extension method with the appropriate signature:

namespace Newtonsoft.Json.Linq
{
    public static class JsonExtensions
    {
        public static void Add(this JObject target, string propertyName, object value) =>
            target.Add(propertyName, JToken.FromObject(value));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.