Is there a better way to parse json document and extract property value of a particular node in C#(.net core), without knowing root property's name? Given: - root of json document will have only one property but property name is unknown. Would prefer to have a solution without using NewtonSoft library but instead System.Text.JSon
Sample json document below:
{
"rootPropertyName": {
"someProperty1": "TCC",
"someProperty2": "128-1600-8routeextent",
"eventType": "RouteUpdated",
---leaving other properties for sake of brevity---
}
}
As seen above, I would like to parse above json document to extract a particular node's value say "eventType" (this property name is known to me) but I don't know the root property name.
Current implementation:
using JsonDocument doc = JsonDocument.Parse(jsonContent);
{
JsonElement root = doc.RootElement;
string rootPropertyName = root.EnumerateObject().First().Name;
var eventType = root.GetProperty(rootPropertyName).GetProperty("eventType").GetString();
var payload = root.GetProperty(rootPropertyName).ToString();
return (eventType, payload);
}
CodePudding user response:
You could deserialize to a Dictionary<string, YourClass>
. There would be a single key rootPropertyName
and the value would be the whole { "someProperty1":...
object
class YourClass
{
public string someProperty1;
public string someProperty2;
public string eventType;
}
var dict = JsonSerializer.Deserialize<Dictionary<string, YourClass>>(jsonContent);
return (dict.Values.First.eventType, dict.Keys.First);
CodePudding user response:
try this
using JsonDocument doc = JsonDocument.Parse(json);
Dictionary<string,string> propertiesDict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,string>>
(doc.RootElement.EnumerateObject().First().Value.ToString());
string someProperty2 = propertiesDict["someProperty2"];
or you can deserialize to a c# object
Properties properties = System.Text.Json.JsonSerializer.Deserialize<Properties>(
doc.RootElement.EnumerateObject().First().Value.ToString());
string someProperty2 = properties.someProperty2;
class
class Properties
{
public string someProperty1 { get; set; }
public string someProperty2 { get; set; }
public string eventType { get; set; }
}
CodePudding user response:
You could use a regex
(?:\"your-key\"\s*\:\s*)((\[((?<g1>[^\[\]] |(?1))*)\])|({((?<g2>[^{}] |(?1))*)})|(\".*\"))
In c# it looks like this
public static string GetValue(string json, string key, string json)
{
var pattern = $"(?:\"{key}\"\\s*\\:\\s*)((\\[((?<g1>[^\\[\\]] |(?1))*)\\])|({{((?<g2>[^{{}}] |(?1))*)}})|(\".*\"))";
var regex = new PCRE.PcreRegex(pattern);
return regex.Match(json).Value;
}
Note : I use the Pcre.Net nugget package because .net's regex doesn't support some features.