将对象序列化为JSON时,DataContract框架无法正常工作

时间:2017-06-27 10:44:07

标签: c# asp.net json datacontract

这是我的模特:

namespace RESTalm
{
    [DataContract]
    [KnownType(typeof(Entity))]
    [KnownType(typeof(Field))]
    [KnownType(typeof(Value))]
    public class Entities
    {
        [DataMember(IsRequired = true)]
        public List<Entity> entities;

        [DataMember(IsRequired = true)]
        public int TotalResults;
    }

    [DataContract]
    [KnownType(typeof(Field))]
    [KnownType(typeof(Value))]
    public class Entity
    {
        [DataMember(IsRequired = true)]
        public Field[] Fields;

        [DataMember(IsRequired = true)]
        public String Type;
    }

    [DataContract]
    [KnownType(typeof(Value))]
    public class Field
    {
        [DataMember(IsRequired = true)]
        public String Name;

        [DataMember(IsRequired = true)]
        public Value[] values;
    }

    [DataContract]
    [KnownType(typeof(Value))]
    public class Value
    {
        [DataMember(IsRequired = true)]
        public String value;
    }    
}

这是我的计划:

        private String toJSON(Object poco)
        {
            String json;
            DataContractJsonSerializer jsonParser = new DataContractJsonSerializer(poco.GetType());
            MemoryStream buffer = new MemoryStream();

            jsonParser.WriteObject(buffer, poco);
            StreamReader reader = new StreamReader(buffer);
            json = reader.ReadToEnd();
            reader.Close();
            buffer.Close();

            return json;
    }

当对象jsonParser初始化时,它似乎根本不能识别我的模型。 这会导致空MemoryStream()。 请帮忙。

P.S。我在我的程序中删除了异常处理,因为它分散了注意力。谢谢。 此外,目前始终假定对象poco是我模型中的类型。

1 个答案:

答案 0 :(得分:1)

您需要先将流重置为Position,然后才能从中读取,例如:

public static string ToJson<T>(T obj, DataContractJsonSerializer serializer = null)
{
    serializer = serializer ?? new DataContractJsonSerializer(obj == null ? typeof(T) : obj.GetType());
    using (var memory = new MemoryStream())
    {
        serializer.WriteObject(memory, obj);
        memory.Seek(0, SeekOrigin.Begin);
        using (var reader = new StreamReader(memory))
        {
            return reader.ReadToEnd();
        }
    }
}