我想要我的类类型的JSON表示,以便我可以将它们插入到客户端模式中。这就是我的服务器端C#类的样子:
public class Person
{
public int ID { get; set; }
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsMarried { get; set; }
}
如何将其序列化为此?:
{
fields: {
"ID": {
type: "number"
},
"Name": {
type: "string",
validation: {
required: true,
message: "Name is required.",
}
},
"Birthday": {
type: "date"
},
"IsMarried": {
type: "bool"
}
}
}
答案 0 :(得分:2)
在JSON.NET库中没有为此做任何事情(AFAIK),但使用一些反射代码实现它相当简单:
public class StackOverflow_19336832
{
public class RequiredAttribute : Attribute
{
public string ErrorMessage { get; set; }
}
public class Person
{
public int ID { get; set; }
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsMarried { get; set; }
}
static JObject GetSchema(Type type)
{
var result = new JObject();
foreach (var prop in type.GetProperties())
{
var name = prop.Name;
var propType = prop.PropertyType;
var field = new JObject();
result.Add(name, field);
switch (Type.GetTypeCode(propType))
{
case TypeCode.Boolean:
field.Add("type", "bool");
break;
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
case TypeCode.Double:
case TypeCode.Single:
field.Add("type", "number");
break;
case TypeCode.String:
field.Add("type", "string");
break;
case TypeCode.DateTime:
field.Add("type", "date");
break;
default:
throw new ArgumentException("Don't know how to generate schema for property with type " + propType.FullName);
}
var req = prop.GetCustomAttributes(typeof(RequiredAttribute), false).FirstOrDefault() as RequiredAttribute;
if (req != null)
{
var validation = new JObject();
field.Add("validation", validation);
validation.Add("required", true);
if (!string.IsNullOrEmpty(req.ErrorMessage))
{
validation.Add("message", req.ErrorMessage);
}
}
}
return result;
}
public static void Test()
{
var schema = GetSchema(typeof(Person));
Console.WriteLine(schema);
}
}
答案 1 :(得分:-1)
在这里查看有关如何使用JavaScriptSerializer
完成工作的一些想法。还有其他序列化器,但这个很好用,链接提供了如何实现和使用它的示例。
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx