有没有一种更简单、更干净的方法来实现这一点?
public class Sidebar
{
[JsonProperty("0")]
public string Hurry = "hurry";
[JsonProperty("1")]
public string Dont_Spam_This_Button = "don't spam this button";
[JsonProperty("2")]
public string Navigation = "navigation";
[JsonProperty("3")]
public string Overview = "overview";
我想对对象进行编号,那么有没有一种方法可以用程序实现,而不是使用属性和手动计数?
是的,您可以使用像下面这样的自定义JsonConverter
来获得您想要的结果:
class NumberedPropertiesConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JObject jo = new JObject();
int count = 0;
foreach (MemberInfo member in value.GetType().GetMembers())
{
object memberVal = null;
if (member.MemberType == MemberTypes.Field)
{
memberVal = ((FieldInfo)member).GetValue(value);
}
else if (member.MemberType == MemberTypes.Property)
{
memberVal = ((PropertyInfo)member).GetValue(value);
}
else
{
continue;
}
JToken token = memberVal != null ? JToken.FromObject(memberVal, serializer) : null;
jo.Add(count.ToString(), token);
count++;
}
jo.WriteTo(writer);
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
要使用转换器,只需用指定自定义转换器类型的[JsonConverter]
属性标记类:
[JsonConverter(typeof(NumberedPropertiesConverter))]
public class Sidebar
{
...
}
一个重要的注意事项是:属性/字段将根据Type.GetMembers()
方法返回的顺序进行编号。通常,这将与类中声明的顺序相匹配;但是,如果您混合了公共属性和公共字段,那么所有属性都将在所有字段之前返回。
这里有一个演示:
public class Program
{
public static void Main()
{
Sidebar sb = new Sidebar();
string json = JsonConvert.SerializeObject(sb, Formatting.Indented);
Console.WriteLine(json);
}
}
[JsonConverter(typeof(NumberedPropertiesConverter))]
public class Sidebar
{
public string Foo { get { return "foo property"; } }
public string Hurry = "hurry";
public string Dont_Spam_This_Button = "don't spam this button";
public string Navigation = "navigation";
public string Overview = "overview";
public string Bar { get { return "bar property"; } }
}
输出:
{
"0": "foo property",
"1": "bar property",
"2": "hurry",
"3": "don't spam this button",
"4": "navigation",
"5": "overview"
}
Fiddle:https://dotnetfiddle.net/aZ51qv
当你想要的东西更像["hurry",...,"overview"]
时,你正在做的事情会给你类似{"0":"hurry",...,"3":"overview"}
的东西
你可以做的是创建一个自定义的转换器/序列化程序,或者如果你不需要在.net中自动序列化/反序列化,只需在类方法中序列化一个对象[]数组。。。
public string AsJson()
{
return JsonConvert.SerializeObject(new object[] {
Hurry, Dont_Spam_This_Button, Navigation, Overview
});
}