0

I am working on a REST API for a project using Visual Studio 2013 with C# and ASP.NET, and I need some guidance.

When the webpage performs a POST, I am passing along a number of fields as a JSON object. By defining a data transfer object in my C# code, I can easily read the values from the JSON, but only if I define all the fields (with the same name).

Here is my current (working) code:

public class AgencyPostDTO
{
    public string AgencyName { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZIP { get; set; }
}

// POST: api/Agency
public string Post(AgencyPostDTO Agency)
{
    int success;
    success = SQLUpdateAgency(Agency);
    if (success < 1)
    {
        return "Failed";
    }
    else
    {
        return "Success";
    }
}

So far no problems. I need to pass the data over to a second function, where I will perform some data processing (including converting the data into XML) and send the data/XML to MS SQL using a stored procedure:

public int SQLUpdateAgency(AgencyPostDTO Agency)
{
    string xml = Agency.SerializeObject();
    ... code to call SQL stored procedure ommitted here
}

Now to my problem. I would prefer if I did not have to define the parameters of the data transfer object AgencyPostDTO in the code, and instead the code would just read the incoming JSON and pass it along to the next function, where I create the XML containing everything passed along. As it works now, if the JSON contains for example an email address field, it will be dropped unless I define it in AgencyPostDTO.

So why do I want to do this? For future ease of maintenance. The users may come and say they want to add additional fields to the web form. I can then simply have our SQL expert add that column to the table, give me the name of it and I add an input field to the HTML form and make sure it is included in the JSON sent over. That way we never have to touch the already written, tested and working code. The new field is simply passed though the whole process.

Can this be done? If so, any suggestions on how?

Karl-Henry Martinsson
  • 2,770
  • 15
  • 25

1 Answers1

1

If you used JSON.NET to handle the deserialisation of your objects then that has support for dynamic properties. Once you'd read your JSON string, you could convert it to a JArray or JObject and from there by using the .Children() call to get a list of all properties to convert it to any XML object you needed.

Have a look here: Deserialize json object into dynamic object using Json.net

Community
  • 1
  • 1
Swomble
  • 874
  • 8
  • 17