Error converting JSON to .Net object in asp.net

前端 未结 4 1643
滥情空心
滥情空心 2020-12-08 18:56

I am unable to convert JSON string to .net object in asp.net. I am sending JSON string from client to server using hidden field (by keeping the JSON object.Tostring() in hid

相关标签:
4条回答
  • 2020-12-08 19:39

    If you want the class to auto-magically serialize into json/xml or deserialize in the object you need to decorate it with some serializable attributes:

    [Serializable, XmlRoot("JsonFeaturedOffer"), DataContract(Name="JsonFeaturedOffer")]
    public class JsonFeaturedOffer  
    {
        [XmlElement ("OfferId"), DataMember(Name="OfferId")]
        public string OfferId {get; set;}
    

    ... and so on

    0 讨论(0)
  • 2020-12-08 19:47

    Unfortunately, none of the proposed solutions solve the real source of the problem. This exception means that your deserializer tries to read from the end of a stream.

    The solution is to rewind the stream to the beginning, ie. set the stream.Position = 0; before deserialization.

    Also, as the comments mention, if you used a StreamWriter you need to flush it before using the stream.

    0 讨论(0)
  • 2020-12-08 19:53

    Instead of doing this manually I would recommend using the built in lightweight JavaScriptSerializer. No attributes are required on the classes you want to serialize/deserialize.

    It's also more flexible and faster than the DataContractJsonSerializer, since it does not have to care about all the wcf stuff. Additionally it has generic overloads that make it very simple to use AND it can also handle anonymous types.

    Serialization:

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var objectAsJsonString = serializer.Serialize(objectToSerialize);
    

    Deserialization:

    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    JsonFeaturedOffer deserializedObject = serializer.Deserialize<JsonFeaturedOffer>(s_JsonBaseDate);
    

    To make it even easier you can create Extension methods that will give you json serialization/deserialization directly on the objects/strings.

    0 讨论(0)
  • 2020-12-08 19:55

    If this is an array of arrays of JsonFeaturedOffers, shouldn't it be:

    byte[] byteArray = Encoding.ASCII.GetBytes(HdnJsonData.Value);
    MemoryStream stream = new MemoryStream(byteArray);
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonFeaturedOffer[][]));
    object result= serializer.ReadObject(stream);
    JsonFeaturedOffer[][] jsonObj = result as JsonFeaturedOffer[][];
    
    0 讨论(0)
提交回复
热议问题