0

I am creating Json file, and before creating i want to check if any of the property is empty of not.. And I want to create abstract method for that. So i dont have to write again and again.

public JObject CreatUserJson(Account lacc)
        {
            JObject pin = new JObject(
                new JProperty("email", lacc.email),
                new JProperty("fullname", lacc.fullname),
                new JProperty("phonenumber", lacc.phonenumber),
                new JProperty("ip_address", lacc.ip_address),
                new JProperty("password", lacc.password),
                new JProperty("client_id", Settings.Globals.CLIENT_ID),
                new JProperty("client_secret", Settings.Globals.CLIENT_SECRET)

        );
            return pin;
        }

This is how i defined my method and there are similar methods like this, I want standard way to check and throw exception if any value is missing..

public JObject IncomingWireNoticeJson(SyanpasePayLib.Resources.Wire lWire)
        {
            JObject pin = new JObject(
                new JProperty("amount", lWire.amount),
                new JProperty("status_url", lWire.status_url),
                new JProperty("memo", lWire.memo),
                new JProperty("oauth_consumer_key", lWire.oauth_consumer_key)
                );
            return pin;
        }

This is other example of method,there is no similarity. I just want to loop through and throw exception if any of the values are missing.

For instance, I know for CreatUserJson I require minimun 4 inputs and max 8 inputs..

Same way for IncomingWireNoticeJson I require minimun 2 inputs and max 4 inputs..

If range is greater then or less then the min and max, then it should throw error.. (This part i can manage, but i dont know how to define standard way to loop through this object)
Can some one help me with this.. ?

nikunjM
  • 560
  • 1
  • 7
  • 21
  • Possible answer: http://stackoverflow.com/a/22683199/3199927 – Tom Jun 08 '15 at 20:32
  • @Tom But i want minimun and max, I dont want to loop through all properties of class account=, I just wan to loop through properties i have defined in my method. – nikunjM Jun 08 '15 at 20:34
  • Sounds like you need a [Json Schema](http://stackoverflow.com/questions/tagged/jsonschema+c%23). – dbc Jun 08 '15 at 21:34

1 Answers1

1

I think JObject has a method called Properties(). So you can loop through the results of that and check whether the values are not null.

foreach (JProperty property in pin.Properties()) 
{
    if (string.IsNullOrWhiteSpace(property.Value)) 
    {
        throw new Exception("Some exception");
        //Or perform count for minimum/maximum check 
    }
}

The minimum and maximum check is also easy todo if you use the Properties() method. Example can be easily rewritten using Linq too, but for explanation and expanding logic purposes I have written the normal version.

Dacker
  • 892
  • 2
  • 8
  • 12