Reputation: 814
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;
Upvotes: 2
Views: 2416
Reputation: 21
Hi first of you make model for Deserialize Object.
Your model like this.
public class Test_Model
{
[JsonProperty("GROUP_MOD_ID")]
public string GROUP_MOD_ID { get; set; }
[JsonProperty("ADMIN")]
public int ADMIN { get; set; }
[JsonProperty("USERS")]
public int USERS { get; set; }
}
and after write this code:
var obj_str = JsonConvert.DeserializeObject<Test_Model>(obj);
int value_admin = obj_str.ADMIN;
Console.WriteLine(value_admin);
if (value_admin == 1)
return true;
else return false;
I hope so your problem sort out.
Upvotes: 0
Reputation: 1
First of all your JSON seems to be incorrect.
Correct JSON:
[{
"GROUP_MOD_ID": "G06",
"ADMIN": 1,
"USERS": 0
}]
And when you desialize this json, it will give you array of array.
You code will be:
dynamic obj_str = JsonConvert.DeserializeObject(json);
string value_admin = obj_str[0].ADMIN;
Console.WriteLine(value_admin);
if (value_admin == "1")
{
}
else
{
}
You can see this by doing this way to.
public class SampleClass
{
public string GROUP_MOD_ID { get; set; }
public int ADMIN { get; set; }
public int USERS { get; set; }
}
Code to deserialize:
SampleClass[] obj_str = JsonConvert.DeserializeObject<SampleClass[]>(json);
int value_admin = obj_str[0].ADMIN;
Console.WriteLine(value_admin);
if (value_admin == 1)
{
}
else
{
}
Upvotes: 2
Reputation: 64
Your code would work only if you have json as
var obj="{'GROUP_MOD_ID':'G06','ADMIN':10,'USERS':0}";
or
var obj="[{'GROUP_MOD_ID':'G06','ADMIN':1,'USERS':0}]";
dynamic obj_str = JsonConvert.DeserializeObject(obj);
string value_admin = obj_str[0]["ADMIN"];
Console.WriteLine(value_admin);
Upvotes: 0
Reputation: 155428
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.
Upvotes: 3