How to get the JSON output only value in C#.
I am trying to use it for type IEnumerable<IEnumerable<CustomType>>
I have class with a property of type IEnumerable<IEnumerable<CustomType>>
and CustomType is defined as
public class CustomType{
public string Type {get;set;}
public string Value {get;set;}
}
var data = JsonConvert.SerializeObject(collection);
The result i am getting is
[
[
{"Type":"Role","Value":"RoleA"},
{"Type":"Role","Value":"RoleB"}
],
[
{"Type":"Role","Value":"RoleC"}
],
[
{"Type":"Buyer","Value":"UserA"}
],
[
{"Type":"Seller","Value":"UserB"}
]
]
I need following output
[
[{"Role" : "RoleA"},{"Role" : "RoleB"}],
[{"Role" : "RoleC"}],
[{"Buyer" : "UserA"}]
]
You can do it like here,
public class CustomType
{
public string Type { get; set; }
public string Value { get; set; }
public Dictionary<string, string> AsJsonProperty()
{
return new Dictionary<string, string>
{
{Type, Value}
};
}
}
class Class1
{
public string ToJson(IEnumerable<IEnumerable<CustomType>> customTypes)
{
var asJsonFriendly = customTypes.Select(x => x.Select(y => y.AsJsonProperty()));
return JsonConvert.SerializeObject(asJsonFriendly);
}
}
When you serialize a dictionary to json, it will be a json object (not array) and keys are going to be property names and values will be property values.
This way is usable especially if your property names contains different characters like {"a property ..": "a value"}