Mike Christensen
Mike Christensen

Reputation: 91686

JSON.NET exception when deserializing an array of GUIDs

I'm using JSON.NET to deserialize AJAX HTTP requests sent in from the browser, and am running into problems with web service calls that use a Guid[] as a parameter. This worked fine when I used the built in .NET serializer.

First off, the raw bytes in the stream look like this:

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

I then call:

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

.Type is System.Guid[]

I then get the exception:

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.

Web service methods that take in a single Guid (not an array) work, so I know JSON.NET is able to convert a string into a GUID, but it seems to blow up when you have an array of strings that you want to deserialize to an array of GUIDs.

Is this a JSON.NET bug, and is there a way to fix this? I suppose I could write my own custom Guid collection type, but I'd rather not.

Upvotes: 3

Views: 9079

Answers (1)

L.B
L.B

Reputation: 116178

You need a wrapper class

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


public class Wrapper
{
    public Guid[] recipeIds;
}

--EDIT--

Using Linq

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

var guids = obj["recipeIds"].Children()
            .Cast<JValue>()
            .Select(x => Guid.Parse(x.ToString()))
            .ToList();

Upvotes: 5

Related Questions