I am dealing with the question to find missing properties in a JSON file compared to a C# class / object.
I got the following code:
Public Class Server
{
string URL { get; set; }
string servername { get; set; }
string project { get; set; }
string type { get; set; }
int number { get; set; }
}
And I got a almost matching JSON-File
{
"URL": "http://www.asdf.com",
"servername": "myServer",
"project": "Testproject"
}
How can I identify missing attributes in the JSON-File missing compared to the Class "Server"? As in this case there are the two missing attributes "type" and "number". When I do a deserialization of the JSON-File into the Class all properties are present as the are initialized with their default value.
...
Server myServer = new Server();
Server myServerJSON = JsonConvert.DeserializeObject<Server >({ "URL": "http://www.asdf.com", "servername": "myServer", "project": "Testproject"});
myServer.compareTo(myServerJSON);
My final goal is the following. I am storing a configuration in JSON-Files and I try to find out, which attributes are missing in the JSON-File after I updated the class model, so I can set these missing values with an default value.
Deserialize it without specifying the cast type:
Server myServer = new Server();
var myServerJSON = JsonConvert.DeserializeObject({ "URL": "http://www.asdf.com", "servername": "myServer", "project": "Testproject"});
Then use reflection to check properties:
var jsontype = myServerJSON.GetType();
var maintype = myServer.GetType();
string[] jp = jsontype.GetProperties().Select(x => x.Name).ToArray();
var result = maintype.GetProperties().Where(x=> !jp.Contains(x.Name))
Well, you can try and check each variable by hand, like so:
Server myServer = new Server();
Server myServerJSON = JsonConvert.DeserializeObject<Server >({ "URL": "http://www.asdf.com", "servername": "myServer", "project": "Testproject"});
myServer.compareTo(myServerJSON);
var val = myServer.GetType().GetProperty("URL").GetValue(myServer, null);
if (myServerJSON.URL === val) {
// ...
}
But I am sure there is a faster way. Keep looking, and I hoped this helped a little bit!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.