Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract Values from JObject

Tags:

json

c#

json.net

I'm trying to extract some values from a Json but I have problems with the data between [ ]

{ 
  attrib1: ""es-BO"",
  attrib2: 2,
  Segment: [
  {
    inAttrib1: ""value1"",
    inAttrib2: ""value2"",
    inAttrib3: ""value3""
  }]
}

for the first values I'm using:

string attrib1 = request.GetValue("attrib1").Value<string>();
.
.
.

but when I'm trying to do:

string inAttrib1 = request.GetValue("inAttrib1").Value<string>();

doesn't work...what can I do?, or exists another way to do the same

like image 692
Edson David Soza Andrade Avatar asked Aug 25 '14 20:08

Edson David Soza Andrade


People also ask

How do you take value from JObject?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

What is JObject parse in C#?

The method JObject. Parse() is a JObject class method. This parse method is used to parse a JSON string into a C# object. It parses the data of string based on its key value. This key value is then used to retrieve the data.


1 Answers

The data between (and including) [] is called an array. Before moving on it might be helpful to look at JSON's home page, specifically at the different data types available.

You need to navigate down to the Segment array, then get the first element, then that element's inAttrib1 property:

string attrib1Value = request["Segment"][0]["inAttrib1"].Value<string>();

Or alternatively:

string attrib1Value = request.SelectToken(@"Segment[0].inAttrib1").Value<string>()
like image 148
Andrew Whitaker Avatar answered Oct 27 '22 00:10

Andrew Whitaker