Json.Net将属性名称设置为数字

时间:2015-02-25 00:46:30

标签: json serialization json.net

是否有一种简短,更干净的方法来实现这一目标?

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";

我希望对象被编号,那么有没有办法以编程方式而不是使用属性和手动计数?

2 个答案:

答案 0 :(得分:1)

是的,你可以使用像这样的自定义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"
}

小提琴:https://dotnetfiddle.net/aZ51qv

答案 1 :(得分:0)

当你想要的更像{"0":"hurry",...,"3":"overview"}

时,你所做的事情会给你["hurry",...,"overview"]之类的东西。

你可以做的是创建自定义转换器/序列化器,或者如果你不需要在.net中自动序列化/反序列化,只需在类方法中序列化一个object []数组......

public string AsJson()
{
  return JsonConvert.SerializeObject(new object[] {
    Hurry, Dont_Spam_This_Button, Navigation, Overview
  });
}