将json数据转换为强类型视图

时间:2015-12-12 06:51:43

标签: javascript c# json model-view-controller

我想将JSON数据转换为model.i尝试通过创建类进行序列化但是我在反序列化时遇到错误

我的json数据

 [{"Name":"Group1","Fields":[{"Field":"EmployeeSCP.Salary","Operator":"lt","Value":"50000","$$hashKey":"object:485"}],"Condition":"0"},
{"Name":"Group2","Fields":[{"Field":"EmployeeSCP.Salary","Operator":"gt","Value":"20000","$$hashKey":"object:495"}],"Condition":"0"},
{"groupCondition":"0"}]

模型

 public class ValidationModelData


{
public string Name { get; set; }
public List<FieldsData> Fields { get; set; }
public string Condition { get; set; }
public string groupCondition { get; set; }
}


public class FieldsData
{
 public string Field { get; set; }
public string Operator { get; set; }
public string Value { get; set; }
}

但是我通过反序列化来获取错误

 ValidationModelData validations = JsonConvert.DeserializeObject<ValidationModelData>(validation.JsonMetaData);

2 个答案:

答案 0 :(得分:0)

我怀疑你忽略了它是一个阵列。所以你可以将它们放在数组或List中,如此

ValidationModelData[] validations = JsonConvert.DeserializeObject<ValidationModelData[]>(validation.JsonMetaData);

答案 1 :(得分:0)

您正在将JSON数组转换为C#对象。你必须使用数组或列表。我更喜欢List over array,因为如果你想添加/删除ValidationModelData,那么调整数组大小是很昂贵的。

List<ValidationModelData> validations = JsonConvert.DeserializeObject<List<ValidationModelData>>(validation.JsonMetaData);