Brian Crist Brian Crist - 17 days ago 8
C# Question

How to get value of item in JSON array c#?

So, please read this detail for more information. I get error at

Method not found: 'System.String System.String.Format(System.IFormatProvider, System.String, System.Object)'.
when i try get value of items of array.

The array is:

{
[
{
"GROUP_MOD_ID": "G06",
"ADMIN": 1,
"USERS": 0
}
]
}


This is snippet code

dynamic obj_str = JsonConvert.DeserializeObject(obj);
string value_admin = obj_str["ADMIN"];
Console.WriteLine(value_admin);
if (value_admin == "1")
return true;
else
return false;


. Thank all.
example picture

Dai Dai
Answer

I wouldn't use dynamic in this case. I generally recommend avoiding dynamic in C#. Instead I prefer the JToken-style approach (in the Newtonsoft.Json.Linq namespace, though it doesn't mean you have to use Linq):

JArray array = JArray.Parse( input );
JObject firstObject = (JObject)array.First;
String adminValue = (String)firstObject.GetValue("ADMIN");

In production you'll want to add input validation code to ensure the input JSON array and object actually has elements and values and handle those errors accordingly.

But if you're certain that the input is correct you can reduce this down to a single-line:

String adminValue = (String)( ((JObject)JArray.Parse( input )).First.GetValue("ADMIN") );

...at the cost of readbility, of course.

Comments