Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip property name in json serialization?

Tags:

json

c#

json.net

I am trying to convert List to json. Structure is as follow:

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

This is producing the result as expected:

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

How can I get the results like:-

{
  "Hello": {
    "en": "Hello"
  },
  "World": {
    "en": "World"
  }
}
like image 888
Afnan Ahmad Avatar asked Nov 19 '18 13:11

Afnan Ahmad


1 Answers

You will need to create a custom JsonConverter that knows how to handle serializing 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);
    }
}

Use the converter so that JsonConvert knows how to handle the serialization.

For example

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);
like image 192
Nkosi Avatar answered Oct 20 '22 18:10

Nkosi