Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize JSON as object or array with JSON.Net [duplicate]

Tags:

json

c#

json.net

I want to know if it is possible to deserialize a JSON object that could either be an object or an array.

Similar to this question: Jackson deserialize object or array

But using JSON.Net.

Example

{
    "response": {
        "status":"success",
        // Could be either a single object or an array of objects.
        "data": {
            "prop":"value"
        }
        // OR
        "data": [
            {"prop":"value"},
            {"prop":"value"}
        ]
    }
}
like image 989
Sam Avatar asked Mar 14 '16 02:03

Sam


2 Answers

I think this solves your problem

string jsonString= "your json string";
var token = JToken.Parse(jsonString);

if (token is JArray)
{
    IEnumerable<Car> cars= token.ToObject<List<Car>>();
}
else if (token is JObject)
{
    Car car= token.ToObject<Car>();
}
like image 90
André Andrade Avatar answered Oct 14 '22 07:10

André Andrade


An alternative would be to write our JsonConverter and use it for deserializing so we can work with static types after conversion.

class JsonDataConverter : JsonConverter
{
    public override bool CanWrite { get { return false; } }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Data);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.ReadFrom(reader);

        if (token is JArray)
            return new Data(token.Select(t => t["prop"].ToString()));
        if (token is JObject)
            return new Data(new[] { token["prop"].ToString() });
        throw new NotSupportedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

[JsonConverter(typeof(JsonDataConverter))]
class Data:List<string>
{
    public Data() : base() { }
    public Data(IEnumerable<string> data) : base(data) { }
}

class Response
{
    public string Status { get; set; }
    public Data Data { get; set; }
}

and an example:

    class Program
    {
        static void Main(string[] args)
        {
            var inputObj = @"{
                     'response': {
                        'status':'success',
                        // Could be either a single object or an array of objects.
                        'data': { 'prop':'value'}

                                 }
                             }";

            var inputArray = @"{
                     'response': {
                         'status':'success',
                         // Could be either a single object or an array of objects.
                         'data':[
                                   { 'prop':'value'},
                                   { 'prop':'value'}
                                ]
                                 }
                              }";

            var obj = JsonConvert.DeserializeAnonymousType(inputObj, new { Response = new Response() });

            foreach(var prop in obj.Response.Data)
                Console.WriteLine(prop);

            var arr = JsonConvert.DeserializeAnonymousType(inputArray, new { Response = new Response() });

            foreach (var prop in arr.Response.Data)
                Console.WriteLine(prop);
        }
}
like image 23
user3473830 Avatar answered Oct 14 '22 05:10

user3473830