我制作了一个jquery过滤器工具,它以json的形式返回我的服务器端过滤数据。我想将它转换为C#类,我也想将任何C#类转换为我的json。
我的json和它的镜像C#类如下:
[{"field":{"label":"Category","value":"category"},"operator":{"label":"any of","value":"in"},"value":{"label":"(Family, Friends)","value":"1,2"}},{"field":{"label":"Age","value":"age"},"operator":{"label":">","value":"gt"},"value":{"label":"18","value":"18"}},{"field":{"label":"Firstname","value":"firstname"},"operator":{"label":"equals","value":"eq"},"value":{"label":"\"test\"","value":"test"}},{"field":{"label":"Lastname","value":"lastname"},"operator":{"label":"equals","value":"eq"},"value":{"label":"\"test2\"","value":"test2"}}]
C#镜像:
public class Field
{
public string label { get; set; }
public string value { get; set; }
}
public class Operator
{
public string label { get; set; }
public string value { get; set; }
}
public class Value
{
public string label { get; set; }
public string value { get; set; }
}
public class RootObject
{
public Field field { get; set; }
public Operator @operator { get; set; }
public Value value { get; set; }
}
我试过这种方式:
public class ViewFilter
{
public List<Field> Fields { get; set; }
public List<Operator> Operators { get; set; }
public List<Value> Values { get; set; }
public List<RootObject> RootObjects { get; set; }
}
public class Field
{
public string label { get; set; }
public string value { get; set; }
}
public class Operator
{
public string label { get; set; }
public string value { get; set; }
}
public class Value
{
public string label { get; set; }
public string value { get; set; }
}
public class RootObject
{
public Field field { get; set; }
public Operator @operator { get; set; }
public Value value { get; set; }
}
我试过了:
var result = JsonConvert.DeserializeObject<List<ViewModel.ViewFilter>>(filter).ToList();
foreach (ViewModel.ViewFilter item in result)
{
}
答案 0 :(得分:3)
接收数据时,请使用NewtonSoft JsonConvert类:
var serializerSettings = new JsonSerializerSettings
{ ContractResolver = new CamelCasePropertyNamesContractResolver() };
var fields = JsonConvert.DeserializeObject<List<RootObject>>(yourString, serializerSettings);
yourString 值是您获取的包含json数据的字符串。
CamelCasePropertyNamesContractResolver负责序列化驼峰大小写中的对象名称,如其名称所示。