Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I have a requirement to create a webservice to expose certain items from a CMS as a web service, and I need some suggestions - the structure of the items is as such:

item
- field 1
- field 2
- field 3
- field 4

So, one would think that the class for this will be:

public class MyItem
{
  public string ItemName { get; set; }
  public List<MyField> Fields { get; set; }
}

public class MyField
{
  public string FieldName { get; set; }
  public string FieldValue { get; set; } //they are always string (except - see below)
}

This works for when its always one level deep, but sometimes, one of the fields is actually a point to ANOTHER item (MyItem) or multiple MyItem (List<MyItem>), so I thought I would change the structure of MyField as follows, to make FieldValue as object;

public class MyField
{
  public string FieldName { get; set; }
  public object FieldValue { get; set; } //changed to object
}

So, now, I can put whatever I want in there. This is great in theory, but how will clients consume this? I suspect that when users make a reference to this web service, they won't know which object is being returned in that field? This seems like a not-so-good design. Is there a better approach to this?

share|improve this question
    
In theory it's great, but you actually won't be able to just make it object. If that works (and I don't remember if it does), at the minimum you will have to put a KnownType attribute on the class and explicitly list the types that may occur. –  Darren Kopp Sep 21 '12 at 15:50
add comment

1 Answer 1

What about changing the structure of MyField class to have a property of type MyFieldValue which has a simple string property and a list of MyItem (to contain a single MyItem or many) e.g.

public class MyField
{
    public string FieldName { get; set; }
    public MyFieldValue FieldValue { get; set; }
}

public class MyFieldValue
{
    public string Text { get; set; }
    public List<MyItem> Items { get; set; }
}

Or a simpler option might be to add the various options as properties to MyField e.g.

public class MyField
{
    public string FieldName { get; set; }
    public string FieldValue1 { get; set; } // With better property names
    public MyItem FieldValue2 { get; set; } // This property may be redundant as you could just add a single instance to the list below
    public List<MyItem> FieldValue3 { get; set; }
}

It would then be up to the consumer to check each property.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.