我有以下类
public class Customer{
public string name {get;set;}
public JObject properties {get;set;} = new JObject();
}
现在我正在添加属性到客户属性
var customer = new Customer();
customer.properties["wow-123:test"] = new {
name = "Mark,
company = new {
name = "LLC",
address = new {
city= "London" } } }
最后我想让它看起来像:
"properties": {
"wow-123:test": [
{
"name": "Mark",
"company": {
"name": "LLC",
"address ": {
"city": "London"
}
}
}
]
}
我一直得到错误,它不能转换为Jtoken。如果我将其更改为ToString,那么它不是JSON格式。我怎样才能做到以上几点呢?
首先,需要显式地将匿名类型对象转换为JToken:
customer.properties["wow-123:test"] = JToken.FromObject(new { ... });
然而,由于您的示例输出显示wow-123:test
的内容是数组(..."wow-123:test": [ { "name":...
),您实际需要的可能是
customer.properties["wow-123:test"] = new JArray(JToken.FromObject(new { ... } ));
将创建一个包含匿名类型对象的单元素数组。
小提琴