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"
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With