patterncsharpMinor
Deserializing JSON in an expression-bodied member
Viewed 0 times
expressionmemberjsondeserializingbodied
Problem
All of these if conditions in the below method have similar pattern, Any ideas to come up with a common method to reduce the duplication in this method?
some case we want all the version, and in some case we want only specific version.
I tried with switch case.
some case we want all the version, and in some case we want only specific version.
I tried with switch case.
public override Func VersionMethod => (jobject, parameters) =>{
bool hasValidObject = false;
if (jobject["swVersion"] != null)
{
_livetv.SoftwareVersion = new VersionInfo(jobject["swVersion"].Value());
hasValidObject = true;
}
if (jobject["hwVersion"] != null)
{
_livetv.HardwareVersion = new VersionInfo(jobject["hwVersion"].Value());
hasValidObject = true;
}
if (jobject["ltvVersion"] != null)
{
_livetv.LTV2Version = new VersionInfo(jobject["ltvVersion"].Value());
hasValidObject = true;
}
if (jobject["ltv3Version"] != null)
{
_livetv.LTV3Version = new VersionInfo(jobject["ltv3Version"].Value());
hasValidObject = true;
}
if (jobject["cricVersion"] != null)
{
_livetv.KAVersion = new VersionInfo(jobject["cricVersion"].Value());
hasValidObject = true;
}
if (jobject["bbVersion"] != null)
{
_livetv.BasebandVersion = new VersionInfo(jobject["bbVersion"].Value());
hasValidObject = true;
}
if (hasValidObject)
{
return GenerateSuccessful();
}
return GenerateUnsuccessful(
"Unable to parse version from request, try again.");
};Solution
We can of course try to optimize it but this would be only an ugly workaround trying to minimize the flaws of the current design.
There are more questions then answers:
You should rethink the entire parsing process and not just this helper method.
There are more questions then answers:
- Why is the the parameter
dynamic?
- Are you trying to parse json?
JObjectsuggests you are and I'm pretty sure this is the wrong way to do it.
- Why do you use such a crazy syntax for a method? The expression bodied members are meant for one-liners and not for such huge blocks.
- Why don't you deserialize the object with
JsonConvert.Deserialize?
- Why don't you decorate the properties like
SoftwareVersionwith the appropriate attribute like[JsonProperty(PropertyName = "swVersion")]
You should rethink the entire parsing process and not just this helper method.
Context
StackExchange Code Review Q#158634, answer score: 5
Revisions (0)
No revisions yet.