2

I have a Json sting like

var Result= [{"CompanyID":32,"Roles":["Admin"]}]

I need to get the value of CompanyID from this.

I tried something like

var obj = JObject.Parse(Result);
int Id=obj["CompanyID"];

but it throwing some error "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."

can anyone help

thanks in advance for help .

Arun
  • 1,402
  • 10
  • 32
  • 59
  • Possible duplicate of [Deserializing JSON data to C# using JSON.NET](http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net) – Maksim Simkin Dec 09 '16 at 08:46

1 Answers1

8

The actual problem is that you are trying to parse this to JObject when you actually have an array of objects. You can first parse it to an array, then index the array to select the only object, and select your CompanyID key then grab the value as an int

var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
// Parse your Result to an Array
var jArray = JArray.Parse(Result);
// Index the Array and select your CompanyID
var obj = jArray[0]["CompanyID"].Value<int>();

Alternatively, you can also map the JSON to a concrete type if it's a structure you will work with often. This is more beneficial as you will have compile time checking - in the event of making a spelling mistake or capitalization error when selecting one of the keys.

class Program
{
    static void Main(string[] args)
    {
        var Result = "[{\"CompanyID\":32,\"Roles\":[\"Admin\"]}]";
        var cList = JsonConvert.DeserializeObject<List<Company>>(Result);

        var obj = cList.First().CompanyID;
    }
}

public class Company
{
    public int CompanyID { get; set; }
    public List<string> Roles { get; set; }
}
ColinM
  • 2,622
  • 17
  • 29