Brian Crist Brian Crist - 1 year ago 193
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"];
if (value_admin == "1")
return true;
return false;

. Thank all.
example picture

Dai Dai
Answer Source

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") ); the cost of readbility, of course.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download