JMarsch JMarsch - 1 year ago 55
JSON Question

How to parse this JSON with strange array

I'm using Newtonsoft's JSON parser to parse results from an external system (the external system is not .net, so they are using a different serialization library).

The JSON string looks kind of funny to me. The endpoint is for /clients, but instead of returning an array of client resources, it returns a named object that contains an array. Like this:

{"Client": [{"ClientId":"TheId"}]}

If I try to deserialize that into a client array, it fails with an exception:

Client[] clients = serializer.Deserialize<Client[]>(aReaderWithTheJson)

The exception:

Cannot deserialize the current JSON object ... 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

I have gotten it to deserialize successfully by creating an artificial wrapper class for my target object like so:

class ClientArray
public Client[] Client {get;set;}

// then deserialize:
var clientWrapper = serializer.Deserialize<ClientArray>(theReader);
var client = clientWrapper.Client[0];

My question though: While this works, Is there some feature of that I don't know about that I should look into (some kind of serialization helper, or an attribute that I could decorate my DTO with?).

Answer Source

You are correct. The JSON you have is well formatted JSON. Nothing funny about it.

It's returning an array of client resources packaged/wrapped in a root object.

{"Client": [{"ClientId":"TheId"}]}

which resolve to this...

public class Client
    public string ClientId { get; set; }

public class RootObject // Same as you wrapper
    public IList<Client> Client { get; set; }

when placed in a JSON deserializer like

Just like you eventually figured out by using your Wrapper object.

var clientWrapper = serializer.Deserialize<RootObject>(json);
var clients = clientWrapper.Client;

This looks exactly like what you have in your question. There is nothing else really for you to do if that is how the external system is providing the data.