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 .

1

1 Answer 1

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; }
}
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.