0

I'm new to Json.net, so I'm not sure if I'm doing this the right / best way, but I can't figure this out:

I'm creating an output JObject:

JObject joOutput = new JObject();

Now, I have a list of paths to values:

a.b.c = 5
a.b.d = 7
a.c.q = 8

So I want to populate the joOutput object in the obvious way using that hierarchy.

I can't seem to find a way to set the value by path, obviously creating the path along the way if it doesn't exist.

I'm trying to split the path on the .'s and create the nodes, but I can't even get that far as the api is very confusing.

Can you point me in the right direction?

Thanks!

3
  • 3
    What do you plan on using joObject for that can't be done with a ? Commented May 19, 2017 at 18:01
  • @JamesCurran with a what? Commented May 19, 2017 at 18:06
  • 1
    With the object a; Commented May 19, 2017 at 18:11

2 Answers 2

2
string a = @"{""b"": {""c"":5, ""d"":7}, ""c"": {""q"":8}}";
JObject joObject = JObject.Parse(a);

UPDATE:

var B = new JObject();
B.Add("c", 5);
B.Add("d", 7);

var C = new JObject();
C.Add("q", 8);


JObject A = new JObject();
A.Add("b", B);
A.Add("c", C);

UPDATE2, for completeness, here is Vladimir's method:

var B = new Dictionary<string, int> { ["c"] = 5, ["d"] = 7 };
var C = new Dictionary<string, int> { ["q"] = 5, ["8"] = 7 };
var A = new Dictionary<string, object> { ["b"] = B, ["c"] = C };

var AA = JObject.FromObject(A);
Sign up to request clarification or add additional context in comments.

4 Comments

I need to create it DYNAMICALLY, that was just an example set. It might be a.q.z on the next run. I just get a list of paths and I need to create the json from that.
@SledgeHammer you do realize that you can put that string together however you want, right?
@ManfredRadlwimmer, the whole point was to use the API instead of creating the string myself.
Ah, I see what the issue was... I was using the JObject incorrectly. I was assuming the name was a property of the object and its not. Thanks.
-1

Try to solve your problem by using Dictionary with string key and object value.

Dictionary<string,object> myJsonObj = new Dictionary<string, object>;

Each element inside can be also same dictionary.

2 Comments

myJsonObj.Add("subElement", new Dictionary<string, object>); myJsonObj["subElement"].Add("subsubElement", 1);
After serialization it will be {"subElement" : { "subsubElement" : 1 } }

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.