8

2012-06-07T00:29:47.000日付があり、逆シリアル化する必要があるjsonがあります。しかし、

 DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
 return (object)serializer.ReadObject(Util.GetMemoryStreamFromString(json));

以下の例外が発生します

There was an error deserializing the object of type System.Collections.Generic.List`1
[[MyNameSpace.MyClass, MyNameSpace, Version=1.0.4541.23433, Culture=neutral, PublicKeyToken=null]].
 DateTime content '2012-06-07T00:29:47.000' does not start with '\/Date(' and end with ')\/' as required for JSON

Windows Mobile 7では機能しますが、同じコードはWindows8では機能しません 。の代わりに
日付形式が必要です。\/Date(1337020200000+0530)\/2012-06-07T00:29:47.000

はいの場合、カスタムシリアル化が必要ですか?また、Androidで同じJSONが使用されているため、使用する必要があり、JSONの形式を変更できません JSON.NET.netは初めてです。ありがとう。DataContractJsonSerializer

4

2 に答える 2

7

シリアル化/逆シリアル化に1つの文字列プロパティを使用し、それをDateTimeに変換する別の非シリアル化プロパティを使用します。いくつかのサンプルコードを見やすくします。

[DataContract]
public class LibraryBook
{
    [DataMember(Name = "ReturnDate")]
    // This can be private because it's only ever accessed by the serialiser.
    private string FormattedReturnDate { get; set; }

    // This attribute prevents the ReturnDate property from being serialised.
    [IgnoreDataMember]
    // This property is used by your code.
    public DateTime ReturnDate
    {
        // Replace "o" with whichever DateTime format specifier you need.
        // "o" gives you a round-trippable format which is ISO-8601-compatible.
        get { return DateTime.ParseExact(FormattedReturnDate, "o", CultureInfo.InvariantCulture); }
        set { FormattedReturnDate = value.ToString("o"); }
    }
}

代わりに、FormattedReturnDateのセッターで解析を実行して、不正な日付を受け取った場合に早期に失敗できるようにすることができます。


シリアル化されたDataMemberに正しい名前を付けるというGôTôの提案を含めるように編集されました。

于 2012-06-08T09:31:11.737 に答える
1

DataContractJsonSerializerコンストラクターでフォーマットを渡します

var serializer = new DataContractJsonSerializer(
   typeof(Client),
   new DataContractJsonSerializerSettings {
       DateTimeFormat = new DateTimeFormat("yyyy-MM-dd hh:mm:ss"),
    });
于 2019-02-27T12:54:51.150 に答える