List<User> list = LoadUsers();
JObject json = new JObject();
json["users"] = new JValue(list);
Run Code Online (Sandbox Code Playgroud)
似乎没有工作?
错误:
Could not determine JSON object type for type System.Collections.Generic.List`1
Run Code Online (Sandbox Code Playgroud) 我正在使用SwiftType Elastic Search + C#并遇到反序列化响应的问题,原因是SwiftType将所有字段作为具有raw属性的对象返回为对象(https://swiftype.com/documentation/app-search/api / search),例如:
{
"meta": {
"warnings": [],
"page": {
"current": 1,
"total_pages": 1,
"total_results": 2,
"size": 10
},
"request_id": "6887a53f701a59574a0f3a7012e01aa8"
},
"results": [
{
"phone": {
"raw": 3148304280.0
},
"accounts_balance_ach": {
"raw": 27068128.71
},
"accounts_balance_pending": {
"raw": "46809195.64"
},
"email": {
"raw": "Brisa34@hotmail.com"
},
"accounts_count": {
"raw": 6.0
},
"id": {
"raw": "c98808a2-d7d6-4444-834d-2fe4f6858f6b"
},
"display_name": {
"raw": "The Johnstons"
},
"type": {
"raw": "Couple"
},
"advisor_email": {
"raw": "Cornelius_Schiller14@hotmail.com"
},
"created_at": …Run Code Online (Sandbox Code Playgroud) 我如何轻松地将此JSON反序列化为OrderDto C#类?有某种方式可以通过属性来做到这一点吗?
JSON:
{
"ExternalId": "123",
"Customer": {
"Name": "John Smith"
}
...
}
Run Code Online (Sandbox Code Playgroud)
C#:
public class OrderDto
{
public string ExternalId { get; set; }
public string CustomerName { get; set; }
...
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用JsonProperty属性,但无法使其正常工作。我的想法是写一个像这样的注释:
[JsonProperty("Customer/Name")]
public string CustomerName { get; set; }
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。有任何想法吗?谢谢!:)
我正在编写一个端点来接受来自第 3 方的 webhook 上的 POST 请求,并且他们发送的数据是 JSON 编码的正文。所以,我无法控制发送给我的数据,我需要处理它。我的问题是他们在他们的 JSON 中做了很多嵌套,因为我只使用了他们发送给我的几个键,我不想创建一堆不必要的嵌套模型来获取我想要的数据。这是一个示例有效负载:
{
id: "123456",
user: {
"name": {
"first": "John",
"Last": "Doe"
}
},
"payment": {
"type": "cash"
}
}
Run Code Online (Sandbox Code Playgroud)
我想把它放在一个看起来像这样的模型中:
public class SalesRecord
{
public string FirstName {get; set;}
public string LastName {get; set;}
public string PaymentType {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
端点示例(还没有多少):
[HttpPost("create", Name = "CreateSalesRecord")]
public ActionResult Create([FromBody] SalesRecord record)
{
return Ok(record);
}
Run Code Online (Sandbox Code Playgroud)
我过去的工作是在 Phalcon PHP 框架中,我通常只是直接访问 POST Body 并自己在模型中设置值。我当然看到了模型绑定的优点,但我还不明白如何正确地解决这种情况。
当尝试使用 更新类属性时,不会JsonConvert.PopulateObject调用JsonPathConverter,因此填充不会完成。
示例类:
[JsonConverter(typeof(JsonPathConverter))]
public class SampleClass
{
int id;
[JsonProperty("sample.id")]
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
拨电至PopulateObject:
var sampleClass = new SampleClass() {
Id = 1
};
var str = "{sample:{id:2}}";
JsonConvert.PopulateObject(str, sampleClass, new JsonSerializerSettings());
Run Code Online (Sandbox Code Playgroud)
但该Id属性永远不会设置为 2。
我已经尝试JsonSerializerSettings过,converter = new JsonPathConverter()但它也不起作用。
知道为什么它不起作用吗?