Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of a JValue object

Tags:

json

c#

json.net

I am using Newtonsoft.Json for parsing Json text. For a reason I need name of JToken or Jvalue object. As per example if "ChoiceId":865 is JValue then I need to get "ChoiceId". But I am trying it for few hours now but could not figure out how. How can I get that name ?

Thanks

EXAMPLE: if this is the json file content:

{"ChoiceId":868,"Choice":"Post","Url":"/pst/goods"}

Then I can get ChoiceId value by using

JObject json = JObject.Parse(hole);
JValue jvalue = (Jvalue)json["ChoiceId"];
string value = jvalue.Value;

But there is no property for getting the name ie."ChoiceId" . So my question is that how can I get it ?

like image 900
Barun Avatar asked Dec 14 '12 22:12

Barun


People also ask

How can I get JProperty from JToken?

You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject . Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty , you can get its Name .

What is Jvalue?

The J value is defined as the elastic potential difference between the linear and nonlinear elastic bodies with the same geometric variables [52,53].

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...


1 Answers

As I've seen none of your code thus I'm spitballing, perhaps you're looking for JToken.Parent and JProperty?

// Assumes token is JToken, search for the owning JProperty
var parentProperty = token.Ancestors<JProperty>()
                          .FirstOrDefault();

// alternatively, if you know it'll be a property:
var parentProperty = ((JProperty)token.Parent);

var name = parentProperty.Name;
like image 111
user7116 Avatar answered Oct 12 '22 11:10

user7116