0

我正在尝试通过包含一些 JSON 的隐藏文本字段将一些数据发布到我的 MVC 3 控制器。我有通过字符串课程列表传入的 JSON。任何人都知道为什么这不起作用?

我所做的只是从 JSON 字符串中生成一个字节 [],将其写入 MemoryStream,然后反序列化该流——或者,尝试这样做。BookCourse bc 总是以空属性结束。

这是我将使用的 JSON 之类的东西:

[{"coursesection":"1234","netlogon":"jsmith","label":"CRSE-1313 Generic Course Titling ~ Joe Smith"}]

这是要反序列化的对象:

using System.Runtime.Serialization;

namespace xxxx.Models
{
    [DataContract]
    public class BookCourse
    {
        [DataMember]
        public string coursesection { get; set; }

        [DataMember]
        public string netlogon { get; set; }

        [DataMember]
        public string label { get; set; }
    }
}

最后,执行它的控制器动作代码——

var byteArray = Encoding.ASCII.GetBytes(coursesList);

// Deserialize byte array to data type
var stream = new MemoryStream();
stream.Write(byteArray, 0, byteArray.Length);
var crs = new DataContractJsonSerializer(typeof(BookCourse));
stream.Position = 0;

// Read stream to object
ad.CourseSectionIDs = new List<int>();
try
{
    var bc = (BookCourse) crs.ReadObject(stream);
    while (bc.coursesection != null)
    {
        cs.AssociateCourseBook(bc.netlogon, bc.coursesection, ad.ISBN);
        bc = (BookCourse)crs.ReadObject(stream);
    }
}
catch (System.Runtime.Serialization.SerializationException e)
{
    // Is this best practice for handling "none"?
}
4

2 回答 2

1

您的 JSON 字符串表示 BookCourse 的集合,而不是单个 BookCourse。所以调整你的代码:

var serializer = new DataContractJsonSerializer(typeof(BookCourse[]));

进而:

var bookCourses = (BookCourse[])crs.ReadObject(stream);

或者,如果您想使用单个 BookCourse,您将需要更改 JSON 字符串并删除代表集合的环绕方括号。

于 2012-10-30T12:57:38.923 回答
1

Darin 是正确的,如果您想在合同级别上进行更改,这里就是更改。

[DataContract]
public class BookCourse
{
    [DataMember]
    public string coursesection { get; set; }

    [DataMember]
    public string netlogon { get; set; }

    [DataMember]
    public string label { get; set; }
}

[DataContract]
public class BookCourceCollection
{
    [DataMember]
    public List<BookCourse> Collection;

    public static BookCourceCollection ReturnCollection(string jsonString)
    {
        MemoryStream ms;
        BookCourceCollection collection;

        using (ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(BookCourceCollection));
            collection = ser.ReadObject(ms) as BookCourceCollection;
        }

        return collection;
    }

}

用法:

 string jsonString = "Your JSON string from the front end";

var bookCourceObject = BookCourseCollection.ReturnCollection(jsonString);
foreach (BookCourse bookCourse in bookCourceObject.Collection)
{
    cs.AssociateCourseBook(bookCourse.netlogon, bookCourse.coursesection, bookCourse.ISBN);
}
于 2012-10-30T13:03:24.240 回答