2

ServiceStack.Textライブラリを使用して、動的に生成されたオブジェクト (匿名型) をシリアル化しています

それは魅力のように機能しますが、次のエラーが発生する状況があります

Unable to cast object of type '<>f__AnonymousType14`2[System.String,<>f__AnonymousType2`10[System.String,System.String,System.String,System.String,System.Int32,System.Int32,System.Int32,System.String,System.String,System.String]]' to type '<>f__AnonymousType14`2[System.String,<>f__AnonymousType13`3[System.String,System.Int32,System.String]]'.

状況は、これは異なるタイプのデータでキーワードを使用して検索し、次のように c# dynamic を使用して結果を返す検索方法です

dynamic data = new
                {
                 ResultType = "Place",
                 Data = new
                         {
                          Name = place.Name,
                          Address = place.Address,
                         }
                 };

Dataサブタイプのプロパティが多かれ少なかれ、別のタイプがこのようになる可能性があります

次に、これらのオブジェクトを List オブジェクトに追加するdataと、うまく機能し、デバッグで結果を確認できます。

ここに画像の説明を入力

しかし、シリアライザーに行くと、このエラーが発生します

私たちを手伝ってくれますか ..

編集:オブジェクトタイプのキーと結果行の値を使用するリストの代わりに辞書を使用して、この問題を部分的に解決しました

var dicResult = new Dictionary<string, dynamic>();
....
dicResult.Add("Category", new
                                      {
                                        Foo = "bar",
                                        .....
                                      }

dicResult.Add("Place", new
                                      {
                                        FooInt = 123,
                                        .....
                                      }

このような結果

{
    .....
    "Data": [
        {
            "Key": "Category",
            "Value": {
                "Foo": "bar",
                ....  
            }
        },
        {
            "Key": "Place",
            "Value": {
                "FooInt": 123,
                .....
             }
        }]
}

しかし、私はまだより良い解決策を探しています

4

0 に答える 0