简体   繁体   中英

Dynamic XML/JSON from WCF Service

I am creating a WCF service which is intended to return data from a database. The data in this database is designed to be as generic as possible so it can be used be used for multiple purposes. There is only one key type called Entity which has a type flag on it which is linked to another table which denotes the EntityType .

Here is the model for these 2 types...

在此处输入图片说明

As an example of how it is going to be used, imagine that the types are Continent , Country , State , City . There is a table that is used to work out the hierarchy of the objects so don't worry about that for simplicity.

This is how the data is coming out in XML form at the moment...

XML数据样例

Ultimately what I want to output is something like this...

样本自定义XML数据输出

The issue is that using the default behaviour of .Net to parse this into XML and/or JSON, it will use my Entity class for the XML Node names and I don't want this to happen. I want the XML Nodes to be named by the EntityType associated with the object.

How could I go about doing this so it remains flexible so I can add another EntityType into the database and the XML/JSON would come out with the relevant XML Node names?

Please ask for more explanation if you need it. Due to the nature of this being quite generic, it made it a little difficult for me to explain here... :)

Since you are working with WCF, the data contract is needed, becouse the client need to know how to handle the response. I think it is not possible to make a dynamic data contract, but you can create specific data contracts for each case and rename the property as follows:

[DataContract(Name = "Continent")]
public class Entity
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }
}

Or you could keep the current Entity data contract and add one more property to identify how the client should interprete the result.

What do you think about that?

Regards,

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM