在MVC中反序列化未命名的对象

时间:2014-05-27 05:37:45

标签: c# asp.net-mvc json

我有以下被认为有效的JSON:

{
    "folderList": [
        [
            {
                "folderPath": "/Test",
                "userList": [
                    {
                        "userName": "Test User",
                        "accessType": "Read Only",
                        "startDate": "2.May.2014",
                        "endDate": "3.May.2014"
                    }
                ]
            }
        ]
    ]
}

问题是你可以看到folderList包含一个没有名字的数组,因此我无法在MVC中正确反序列化。它拉动当前的项目数(在这种情况下为1),但所有值最终都为空。

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

它是一个包含列表的列表(如果您愿意,还包含包含数组的数组)。

// Users that got access to a specific folder item
public class User
{
    public string userName {get; set; }
    public string accessType{get; set; }
    public string startDate {get; set; }
    public string endDate {get; set; }
}

// Inner object
public class FolderListItem
{
    public string folderPath { get; set; }
    public User[] userList { get; set; }
}

// See? List of Lists
public class RootObject
{
    public List<List<FolderListItem>> folderList { get; set; }
}

// Need to have a root object as the folder list is named.
public ActionResult SomeMethod(RootObject data)
{
}

答案 1 :(得分:1)

看看这个答案。

https://stackoverflow.com/a/3806407/992021

我过去曾经使用它,并且能够解决我无法控制我收到的JSON有效负载的问题。

否则,其中一种方法是通过使用JSON解串器的解决方案。当您只需要JSON有效负载中的值而不能或不想创建要反序列化的实际对象时,这非常有用。

JSON.net

dynamic jsonObject = JsonConvert.DeserializeObject("{ 'Name': 'Jon Smith', 'Address': {         'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = jsonObject.Name;
string address = jsonObject.Address.City;

还使用Newtonsoft.Json.Linq:

dynamic jsonObject = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");

string name = jsonObject.Name;
string address = jsonObject.Address.City;

答案 2 :(得分:0)

你必须创建像

这样的类
public class Folder
{
 public string folderPath{get;set;}
 public List<USER> userList{get;set;}
}
public class USER
{
public string userName{get;set;}
public string accessType{get;set;}
public string startDate{get;set;}
public string endDate{get;set;}
}