简体   繁体   English

将对象序列化为JSON时,DataContract框架不起作用

[英]DataContract framework not working when serializing objects to JSON

Here is my model: 这是我的模型:

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;
    }    
}

Here is my program: 这是我的程序:

        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;
    }

When the object jsonParser initializes it doesn't seem to recognize my model at all. 当对象jsonParser初始化时,它似乎根本无法识别我的模型。 This leads to an empty MemoryStream() . 这导致一个空的MemoryStream() Please help. 请帮忙。

PS I have cut-out exception-handling in my program because it's distracting. PS我的程序中有异常的异常处理,因为它分散了注意力。 Thanks. 谢谢。 Also, for the moment the object poco is always assumed to be a type in my model. 此外,目前在我的模型中始终假定对象poco是一种类型。

You need to rewind the stream to the beginning by resetting its Position before you can read from it, for instance like so: 您需要先重设流的Position然后重新设置流的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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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