1

Hey all I have the following code:

try {
  foreach (var x1 in JObject.Parse(json1)) {
     string name = x1.Key;
     JToken value = x1.Value;

There are no visible errors with the above code. However, once I run the application and it gets to that point it errors and says:

'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'Key'

So whats going on here. My VB.net code works like the above:

Try
    For Each x1 In JObject.Parse(json1)
       Dim name As String = x1.Key
       Dim value As JToken = x1.Value
1
  • Not sure why VB would work, nor why the compiler wouldn't catch it (unless that setup uses dynamic), but I believe the property you're looking for is actually Name. Commented Feb 1, 2016 at 21:19

1 Answer 1

1

JProperty (you get JPropertys by iterating over a JObject) inherits from JContainer, which inherits from JToken. JToken implements IDynamicMetaObjectProvider.

This makes it essentially a dynamic object, which allows you to access anything on it at compile time. That's why you dont get a compiler error.

At runtime the DLR discovers that there is no Key property on x1 and throws that exception.

If you want to get the property name, you should use the Name property.

foreach (var x1 in JObject.Parse(json1)) {
    string name = x1.Name;
    JToken value = x1.Value;
Sign up to request clarification or add additional context in comments.

Comments

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.