I have a model classes like below
public class A
{
public string Name{get;set;}
public string Value{get;set;}
}
public class B
{
public List<A>Items{get;set;}
}
The below json will be deserialized to class B
{
"Items":[
{
"Name":"Food Name"
"Value":"Fries"
},
{
"Name":"Weapon Name"
"Value":"Gun"
},
{
"Name":"Vehicle Name"
"Value":"Car"
},
{
"Name":"Pet Name"
"Value":"Mewto"
},
{
"Name":"Personal Name"
"Value":"Leo"
}]}
Once the values are deserialized to the class B, I need to validate whether the list item contains Name Food Name,Personal Name,Weapon Name and Car Name and Value for these mentioned items are not null or empty. What is the best approach for this?
CodePudding user response:
You could go for something like
List<A> Items = //however you get the list
string[] names = {"Food Name","Personal Name","Weapon Name", "Car Name"};
foreach (string s in names)
{
var item = Items.FirstOrDefault(i => i.Name == s);
if (item == null || String.IsNullOrWhiteSpace(item.Name))
{
// handle the missing data
break;
}
}
This is likely an ugly solution, but it should work. Also take note, that this doesn't check for any other items in the list. You could have an item where Name is George and Value could be Potato, just as long as you also have the items with correct names.
CodePudding user response:
try this
var jsonParsed=JsonConvert.DeserializeObject<B>(json);
var names =new string[] {"Food Name","Personal Name","Weapon Name","Car Name" };
var valid= jsonParsed.Items.Count(i=> names.Contains(i.Name) && !string.IsNullOrEmpty(i.Value))==names.Length;
