如何获得在MVC 3控制器动态创建的JSON数据集? [英] How to get a dynamically created Json data set in MVC 3 controller?

查看:72
本文介绍了如何获得在MVC 3控制器动态创建的JSON数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,我使用MVC 3,它是在反序列化一个JSON数据集分成传递给我的控制器操作的强类型的对象大。不幸的是我还没有找到一个解决方案,以一个更加动态的情况。

Ok, so I am using MVC 3 and it is great at de-serializing a JSON data set into a strongly typed object that is passed to my controller action. Unfortunately I have not found a solution to a more dynamic case.

是否内置JSON中反序列化和类有一个未定义属性集的支持?例如可以说我有喜欢的名字和年龄的一些固定的数据,但我也想通过降低动态创建等级列表,用户可以输入(或选择)电影,并在表中设置等级值。

Does the built in Json de-serialisation and classes have support for an "undefined" property set? For example lets say I have some fixed data like name and age, but I also want to pass down a dynamically created rating list where the user could enter (or select) a movie and set a rating value in a table.

该模型的数据结构可以是这样的:

The model data structure could be something like this:

public class UserRatings
{
  public string Name { get; set; }
  public int Age { get; set; }
  public Dictionary<string,int> Ratings { get; set; }
}

不过,假设我的Json数据看起来像这样的javascript:

But assuming that my Json dataset looks like this from javascript:

var data = { Name: name, Age: age, Ratings: rating };

凡等级变量是一个动态构造的对象,包括电影的关键和额定值号的名称(或标识)的。当然,在控制器动作的这种反序列化是不会成功的,因为它不理解评级的映射到相当复杂的字典对象。但有一个通用的Json集合,我可以代替使用等级作为中间格式?

Where the rating variable is a dynamically constructed object that consist of the name (or id) of of the movie as key and rating as number. Naturally de-serialization of this in the controller action will not be successful as it does not understand the mapping of Ratings to the rather complex dictionary object. But is there a generic Json collection that I could use instead for Ratings as an intermediate format?

我曾尝试作出评价对象一个JSON字符串中的JavaScript,只是发送一个字符串下来,但我无法找到一个工厂或东西,可以让在C#中的JSON结构,我可以遍历得到数据输出。这些类的Json JsonResult 并不能帮助我在这方面似乎。基本上我怎么可以使用内置的JSON支持MVC中做我自己的反序列化到一些通用的Json集合对象?

I have tried making the Ratings object a Json string in javascript and just sending a string down, but I am unable to find a "factory" or something that can make a Json structure in C# that I can iterate over to get the data out. The classes Json and JsonResult does not help me in this regard it seems. Basically how can I use the built in Json support in MVC to do my own de-serialisation into some generic Json collection object?

推荐答案

您可以使用<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx\"相对=nofollow>的JavaScriptSerializer 或<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx\"相对=nofollow>的DataContractSerializer 一些ActionFilters。他们是非常灵活的。

You Could Use JavaScriptSerializer or DataContractSerializer with Some ActionFilters. They're very flexible

这篇关于如何获得在MVC 3控制器动态创建的JSON数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆