3

ブラウザーから送信された AJAX HTTP 要求を逆シリアル化するために JSON.NET を使用していますが、Guid[] をパラメーターとして使用する Web サービス呼び出しで問題が発生しています。組み込みの .NET シリアライザーを使用した場合、これは正常に機能しました。

まず、ストリーム内の生のバイトは次のようになります。

System.Text.Encoding.UTF8.GetString(rawBody);
"{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}"

次に、次のように呼び出します。

Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
parameters[0] = serializer.Deserialize(sr, operation.Messages[0].Body.Parts[0].Type);

.TypeSystem.Guid[]

次に、例外が発生します。

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Guid[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Path 'recipeIds', line 1, position 13.

単一の Guid (配列ではない) を受け取る Web サービス メソッドは動作するので、JSON.NET が文字列を GUID に変換できることはわかっていますが、逆シリアル化したい文字列の配列があると爆発するようです。 GUID の配列に。

これは JSON.NET のバグですか? これを修正する方法はありますか? 独自のカスタム Guid コレクション型を作成できると思いますが、そうはしません。

4

1 に答える 1

5

ラッパークラスが必要です

string json = "{\"recipeIds\":[\"d9ede305-d244-483b-a435-abcf350efdb2\"]}";
var obj = JsonConvert.DeserializeObject<Wrapper>(json);


public class Wrapper
{
    public Guid[] recipeIds;
}

- 編集 -

Linq の使用

var obj = (JObject)JsonConvert.DeserializeObject(json);

var guids = obj["recipeIds"].Children()
            .Cast<JValue>()
            .Select(x => Guid.Parse(x.ToString()))
            .ToList();
于 2012-11-30T07:04:18.217 に答える