Consider this Json object:
{
"main": {
"2058": {
"id": "2058",
"name": "foo",
"attrib1": "17",
"domain": "somewhere.net",
"enabled": "1",
"permissions": [
"admin",
"user",
"guest",
"vpn",
"power"
]
}
},
"validate": {
"2058": {
"id": "2058",
"name": "foo",
"attrib1": "17",
"domain": "somewhere.net",
"enabled": "1",
"permissions": [
"admin",
"user",
"guest",
"vpn",
"power"
]
}
},
"result": "ok"
}
Between "enabled" and "permissions", there are quite a few hundred more pairs witch i left out. The "validate" part is an exact copy of "main" and the "result" is, well ya, the result.
I want to get 2 specific values from the main section. "id" and "domain". I use the following code to do so.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
namespace JsonParse
{
class Program
{
static void Main()
{
string json = "{" +
"\"main\":{" +
"\"2058\":{" +
"\"id\":\"2058\"," +
"\"name\":\"foo\"," +
"\"attrib1\":\"17\"," +
"\"domain\":\"somewhere.net\"," +
"\"enabled\":\"1\"," +
"\"permissions\":[\"admin\",\"user\",\"guest\",\"vpn\",\"power\"]" +
"}" +
"}," +
"\"validate\":{" +
"\"2058\":{" +
"\"id\":\"2058\"," +
"\"name\":\"foo\"," +
"\"attrib1\":\"17\"," +
"\"domain\":\"somewhere.net\"," +
"\"enabled\":\"1\"," +
"\"permissions\":[\"admin\",\"user\",\"guest\",\"vpn\",\"power\"]" +
"}" +
"}," +
"\"result\":\"ok\"" +
"}";
foreach (KeyValuePair<string, object> item in JsonSerializer.Deserialize<Dictionary<string, object>>(json))
{
if (item.Key == "main")
{
Dictionary<string, object> pairs = JsonSerializer.Deserialize<Dictionary<string, object>>(item.Value.ToString());
Dictionary<string, object> pairs1 = JsonSerializer.Deserialize<Dictionary<string, object>>(pairs.First().Value.ToString());
foreach (KeyValuePair<string, object> valuePair in pairs1)
{
if (valuePair.Key == "id" || valuePair.Key == "domain")
{
Console.WriteLine("Key: " + valuePair.Key + "\nValue: " + valuePair.Value);
}
}
}
}
}
}
}
From this, i get "2058" and "somewhere.net" but is there are more elegant way to get the values instead of deserialize 3 times?