简体   繁体   中英

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. This leads to an empty MemoryStream() . Please help.

PS I have cut-out exception-handling in my program because it's distracting. Thanks. Also, for the moment the object poco is always assumed to be a type in my model.

You need to rewind the stream to the beginning by resetting its Position before you can read from it, for instance like so:

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

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