How to Get a List of Keys from JSON.Net

How can I get a list of keys from Json.NET?

IList<string> keys = parent.Properties().Select(p => p.Name).ToList();

Documentation: JObject.Properties

How to get list of values by key's name across Json using C#

Use the DescendantsAndSelf().OfType() to get all JProperties, and then filter with LINQ.

var root = (JContainer)JToken.Parse(json);
var list = root.DescendantsAndSelf().OfType<JProperty>().Where(p => p.Name == "objectId").Select(p => p.Value.Value<string>());
Console.WriteLine(string.Join(",", list.ToArray()));

How to get all not exist keys after JsonConvert DeserializeObject in Json.Net?

Your problem is twofold:

  1. Find the missing fields
  2. Find the extra fields

Before we are digging into the details let's split the CharaData into two classes

[Serializable]
public class CharaData
{
public int Hp;
public PlayerInfoData PlayerInfo;
}

[Serializable]
public class PlayerInfoData
{
public int Atk;
public int Def;
public int Spd;
}

Missing Fields

This solution relies on the JsonSchema

private static Lazy<JSchema> schema = new Lazy<JSchema>(() => {
var generator = new JSchemaGenerator();
return generator.Generate(typeof(CharaData));
}, true);

public static void ReportMissingFields(string json)
{
var semiParsed = JObject.Parse(json);

try
{
semiParsed.Validate(schema.Value);
}
catch (JSchemaValidationException ex)
{
Console.WriteLine(ex.ValidationError.Message);
}
}
  • schema stores the json schema of CharaData in a lazy fashion
  • Validate compares the json against the schema and if there is a mismatch then it throws a JSchemaValidationException
    • It exposes a property which type is ValidationError which contains a lots of information about the mismatch

Extra fields

This solution relies on JsonExtensionDataAttribute

[Serializable]
internal class CharaDataExtras: CharaData
{
[JsonExtensionData]
public IDictionary<string, JToken> ExtraFields;
}

...

public static void ReportExtraFields(string json)
{
var result = JsonConvert.DeserializeObject<CharaDataExtras>(json);
foreach (var field in result.ExtraFields)
{
Console.WriteLine($"An extra field has found, called {field.Key}");
}
}
  • I've defined the CharaData as class to be able to derive from it << CharaDataExtras
  • Every extra field will be put into the ExtraFields dictionary

Usage

var json = File.ReadAllText("sample.json");
ReportMissingFields(json);
ReportExtraFields(json);

The output:

Required properties are missing from object: Spd.
An extra field has found, called Mp

Get Key Name from nested json object

I believe what you are looking for is to get the properties of the sites. Since accessing the rss["zone1"]["sites"] returns a JToken, you will need to convert that to JObject and then use Properties() method to get the data you need.

var sites = ((JObject)rss["zone1"]["sites"]).Properties();

Then you can simply iterate over the IEnumerable<Jproperty> to get the Name of the property or whatever else you need from under it.

To get the section.Key for the sites, you can use the following code.

foreach(var site in (JObject)rss["zone1"]["sites"]) {
Console.WriteLine(site.Key);
}

Output:

site1
site2

Get the value of the Key from a Json Array

I would mention, if you can change data format, consider doing so, having payload as part as a member proper name is highly unusual but you could do like this:

    [Fact]
public void DynamicJsonHandlingTest()
{
var serialized = "[{\"data\":{\"_hash\":null,\"kind\":\"ENTITY\",\"id\":\"test122\",\"payload\":{\"attributes\":{\"bbl:27\":false},\"relations\":{\"bbl:45\":\"P18\",\"bbl:P18\":\"P562\"},\"type\":[\"P185\"]}}}]";
using var jDoc = JsonDocument.Parse(serialized);
var enumerator = jDoc.RootElement.EnumerateArray();
foreach(var JsonElement in enumerator)
{
var relationsElement = JsonElement.GetProperty("data").GetProperty("payload").GetProperty("relations");

foreach (var ele in relationsElement.EnumerateObject())
{
var sought = ele.Name.Split(":")[1];
//sought now cointains first 45 then P18
}
}
}

Retrieve all JSON key's values from JSON without known structure

private static IEnumerable<string> Flat(JToken token)
{
switch (token.Type)
{
// nested value types
case JTokenType.Object:
case JTokenType.Array:
case JTokenType.Property:
foreach (var item in token.Children().Select(Flat).SelectMany(x => x))
yield return item;
break;
default: // primitive values: int, string, float
yield return token.ToString();
break;
}
}

static async Task Main(string[] args)
{
JToken token = Newtonsoft.Json.JsonConvert.DeserializeObject<JToken>(File.ReadAllText("test.json"));
foreach (var item in Flat(token))
{
Console.WriteLine(item);
}
}

Here is the test output
https://ctrlv.cz/TvqP

VB.NET Get list of keys from json deserialized object

By default, it is deserializing into a Dictionary(Of String, Object) object, as the error message says. Therefore, you just need to loop through the list of dictionary entries:

For Each entry As KeyValuePair(Of String, Object) In j
Console.WriteLine("Key = " & entry.Key)
Console.WriteLine("Value = " & entry.Value)
Next

Or, if you just need the key names:

j.Select(Function(entry) entry.Key)

how to get the key from json object and convert into an array?

You could install json.net and use LINQ to JSON to query the properties:

var jsonString = @"{
""Date"": ""2016-12-15"",
""Data"": {
""A"": 4.4023,
""AB"": 1.6403,
""ABC"": 2.3457
}
}";

var root = JToken.Parse(jsonString);

var properties = root
// Select nested Data object
.SelectTokens("Data")
// Iterate through its children, return property names.
.SelectMany(t => t.Children().OfType<JProperty>().Select(p => p.Name))
.ToArray();

Console.WriteLine(String.Join(",", properties)); // Prints A,AB,ABC

Sample fiddle.

C# find JSON value based only on Key name through multiple levels of array

You could also use linq and filter the JProperty collection based on JProperty.Name. For example

var result = JObject.Parse(jsonString)
.DescendantsAndSelf()
.OfType<JProperty>()
.Single(x=>x.Name.Equals("terminalSize"))
.Value;


Related Topics



Leave a reply



Submit