如何在C#中仅获取JSON输出值。
我正在尝试将其用于IEnumerable<IEnumerable<CustomType>>
我的课程属性为IEnumerable<IEnumerable<CustomType>>
和CustomType定义为
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"}]
]
答案 0 :(得分:1)
你可以这样做,
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);
}
}
将字典序列化为json时,它将是一个json对象(而不是数组),键将成为属性名称,值将是属性值。
这种方法特别适用于您的属性名称包含不同的字符,例如{“a property ..”:“a value”}
答案 1 :(得分:1)
如何将CustomType
转换为字典? (您不需要更改CustomType
课程)
string json = JsonConvert.SerializeObject(collection.Select(innerList =>
innerList.Select(type => new Dictionary<string,object>()
{
{
type.Type, type.Value
}
})));
答案 2 :(得分:0)
var formatedCollections = collection.Select(c => c.Select(nest => new Dictionary<String,String>(){{nest.Type,nest.Value}})).ToArray();
然后序列化formatedCollection