WebAPI列表<t>序列化XML / JSON输出</t>

时间:2013-10-18 14:17:25

标签: c# xml json serialization asp.net-web-api

我尝试在 ApiController 中创建一个如下所示的方法:

public DemoList<Demo> GetAll()
{
    var result = new DemoList<Demo>() { new Demo(){Y=2}, new Demo(), new Demo(){Y=1} };
    result.Name = "Test";
    return result;
}

演示和演示列表如下所示:

public interface INamedEnumerable<out T> : IEnumerable<T>
{
    string Name { get; set; }
}

public class Demo
{
    public int X { get { return 3; } }
    public int Y { get; set; }
}

public class DemoList<T> : List<T>, INamedEnumerable<T>
{
    public DemoList()
    {
    }

    public string Name { get; set; } 
}

然后我用fiddler

取消了输出
GET http://localhost:8086/api/Demo

并得到以下内容:

XML (接受标头设置为application / xml)

<ArrayOfDemo xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/XXX.WebAPI"><Demo><Y>2</Y></Demo><Demo><Y>0</Y></Demo><Demo><Y>1</Y></Demo></ArrayOfDemo>

JSON(Accept header设置为application / json)

[{"X":3,"Y":2},{"X":3,"Y":0},{"X":3,"Y":1}]

我的问题很简单:为什么X变量没有使用XML版本序列化(我认为readonly属性是序列化的)更重要的是,为什么在这两种情况下都是Name属性(哪个是可写的)没有序列化? 有什么方法可以让我的工作像我预期的那样?

编辑: 请注意,我正处于WebAPI环境中!默认情况下,XmlSerializer自动设置为XmlMediaTypeFormatter,JSONSerializer设置为JsonMediaTypeFormatter

3 个答案:

答案 0 :(得分:1)

这似乎是一个错误...使用以下解决方法制定了诀窍:

public class ListWrapper<T>
{
    public ListWrapper(INamedEnumerable<T> list)
    {
        List = new List<T>(list);
        Name = list.Name;
    }

    public List<T> List { get; set; }

    public string Name { get; set; }
}

答案 1 :(得分:0)

XML序列化程序仅允许使用“set”提供的属性序列化。

答案 2 :(得分:0)

您使用什么来序列化它?如果您不需要属性,可以按照here使用DataContractSerializer。默认情况下,没有set的属性不会被序列化,但是使用DataContractSerializer或实现IXmlSerializable应该可以帮到你。

using System;
using System.Runtime.Serialization;
using System.Xml;
[DataContract]
class MyObject {
    public MyObject(Guid id) { this.id = id; }
    [DataMember(Name="Id")]
    private Guid id;
    public Guid Id { get {return id;}}
}
static class Program {
    static void Main() {
        var ser = new DataContractSerializer(typeof(MyObject));
        var obj = new MyObject(Guid.NewGuid());
        using(XmlWriter xw = XmlWriter.Create(Console.Out)) {
            ser.WriteObject(xw, obj);
        }
    }
}