SledgeHammer
SledgeHammer

Reputation: 7736

Json.Net, how to create json dynamically by path?

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!

Upvotes: 0

Views: 2126

Answers (2)

James Curran
James Curran

Reputation: 103585

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);

Upvotes: 2

Vladimir  Chikrizov
Vladimir Chikrizov

Reputation: 389

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.

Upvotes: -1

Related Questions