如何在json序列化中跳过属性名称?

时间:2018-11-19 13:55:10

标签: c# json json.net

我正在尝试将List转换为json。结构如下:

public class ResourceCollection 
{
     public string Name { get; set; }
     public Resources Resources { get; set;}
}

public class Resources
{ 
    public string en { get; set; }
}

List<ResourceCollection> liResourceName = new List<ResourceCollection>();
//section to add the objects in list
string json = JsonConvert.SerializeObject(liResourceName, Newtonsoft.Json.Formatting.Indented);

这将产生预期的结果:

[
   {
     "Name": "Hello",
     "Resources": 
      {
        "en": "Hello" 
      }
   },
   {
     "Name": "World",
     "Resources": 
      {
        "en": "World"
      }
   }
]

我如何获得如下结果:-

{
  "Hello": {
    "en": "Hello"
  },
  "World": {
    "en": "World"
  }
}

1 个答案:

答案 0 :(得分:6)

您将需要创建一个自定义JsonConverter,它知道如何处理序列化ResourceCollection

public class ResourceCollectionConverter : JsonConverter<List<ResourceCollection>> {
    public override bool CanRead {
        get {
            return false; //because ReadJson is not implemented
        }
    }

    public override List<ResourceCollection> ReadJson(JsonReader reader, Type objectType, List<ResourceCollection> existingValue, bool hasExistingValue, JsonSerializer serializer) {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, List<ResourceCollection> value, JsonSerializer serializer) {
        var obj = new JObject(); // { }

        foreach (var item in value) {
            //{ "Hello" : { "en": "Hello" } }
            obj[item.Name] = JObject.FromObject(item.Resources);
        }

        obj.WriteTo(writer);
    }
}

使用转换器,以便JsonConvert知道如何处理序列化。

例如

List<ResourceCollection> liResourceName = new List<ResourceCollection>();

liResourceName.Add(new ResourceCollection { Name = "Hello", Resources = new Resources { en = "Hello" } });
liResourceName.Add(new ResourceCollection { Name = "World", Resources = new Resources { en = "World" } });

var formating = Newtonsoft.Json.Formatting.Indented;
var converter = new ResourceCollectionConverter();
string json = JsonConvert.SerializeObject(liResourceName, formating , converter);