Newtonsoft.Json 无法解析 DateTimeOffset 值的原因是什么?

huangapple go评论62阅读模式
英文:

Why is Newtonsoft.Json failing to parse a DateTimeOffset value?

问题

我正在使用.NET框架和Newtonsoft.JSON包对我的对象进行序列化。我的对象中有一个DateTimeOffset,并且在JSON字符串中导致以下错误:

Newtonsoft.Json.JsonSerializationException Error converting value

JSON字符串格式有什么问题?

公共部分类ConsumeWalletRequest是API的输入参数。

这个类的输入参数是API的输入参数。

英文:

I'm using .NET framework and Newtonsoft.JSON package to serialize my object. I have a DateTimeOffset in my object and

{"body":"{ "transactionDate": "2022-02-12T01:22:33+00:00" }"}

causes following error :

Newtonsoft.Json.JsonSerializationException Error converting value 

What is wrong in JSON string format?

public partial class ConsumeWalletRequest
{
    

    [Newtonsoft.Json.JsonProperty("transactionDate", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Include)]
    public System.DateTimeOffset TransactionDate { get; set; }

}

this class is input parameter of an api

public virtual System.Threading.Tasks.Task<ConsumeWalletResponseApiResultModel> PostConsumeWalletAsync(ConsumeWalletRequest body)
        {
            return PostConsumeWalletAsync(body, System.Threading.CancellationToken.None);
        }

答案1

得分: 0

You don't have valid JSON. You have some kind of embedding going on, and it contains quotes around an incorrectly escaped JSON-stringified object.

{"body":"{ \"transactionDate\": \"2022-02-12T01:22:33+00:00\" }"}

If you wanted to correctly escape it you would escape the " with \ (this is separate from C# string quoting).

{"body":"{ \"transactionDate\": \"2022-02-12T01:22:33+00:00\" }}"

But what you actually want is probably

{"body":{"transactionDate": "2022-02-12T01:22:33+00:00"}}

See repro here.

I suggest you check how this JSON is generated, because no good JSON parser would create this.

英文:

You don't have valid JSON. You have some kind of embedding going on, and it contains quotes around an incorrectly escaped JSON-stringified object.

{"body":"{ "transactionDate": "2022-02-12T01:22:33+00:00" }"}

If you wanted to correctly escape it you would escape the " with \ (this is separate from C# string quoting).

{"body":"{ \"transactionDate\": \"2022-02-12T01:22:33+00:00\" }}

but what you actually want is probably

{"body":{ "transactionDate": "2022-02-12T01:22:33+00:00" }}

See repro here.

I suggest you check how this JSON is generated, because no good JSON parser would create this.

huangapple
  • 本文由 发表于 2023年5月11日 15:00:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76224892.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定