[c#] How do I deserialize a complex JSON object in C# .NET?

I have a JSON string and I need some help to deserialize it.

Nothing worked for me... This is the JSON:

{
    "response": [{
        "loopa": "81ED1A646S894309CA1746FD6B57E5BB46EC18D1FAff",
        "drupa": "D4492C3CCE7D6F839B2BASD2F08577F89A27B4ff",
        "images": [{
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "7e6ffe36e-8789e-4c235-87044-56378f08m30df",
                "market": 1
            },
            {
                "report": {
                    "nemo": "unknown"
                },
                "status": "rock",
                "id": "e50e99df3-59563-45673-afj79e-e3f47504sb55e2",
                "market": 1
            }
        ]
    }]
}

I have an example of the classes, but I don't have to use those classes. I don't mind using some other classes.

These are the classes:

public class Report
{
    public string nemo { get; set; }
}

public class Image
{
    public Report report { get; set; }
    public string status { get; set; }
    public string id { get; set; }
    public int market { get; set; }
}

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject
{
    public Response[] response { get; set; }
}

I want to mention that I have Newtonsoft.Json already, so I can use some functions from there.

How can I do this?

This question is related to c# .net json deserialization

The answer is


I am using following:

    using System.Web.Script.Serialization;       

    ...

    public static T ParseResponse<T>(string data)
    {
        return new JavaScriptSerializer().Deserialize<T>(data);
    }

I also had the issue of parsing and using JSON objects in C#. I checked the dynamic type with some libraries, but the issue was always checking if a property exists.

In the end, I stumbled upon this web page, which saved me a lot of time. It automatically creates a strongly typed class based on your JSON data, that you will use with the Newtonsoft library, and it works perfectly. It also works with languages other than C#.


You can solve your problem like below bunch of codes

public class Response
{
    public string loopa { get; set; }
    public string drupa{ get; set; }
    public Image[] images { get; set; }
}

public class RootObject<T>
    {
        public List<T> response{ get; set; }

    }

var des = (RootObject<Response>)Newtonsoft.Json.JsonConvert.DeserializeObject(Your JSon String, typeof(RootObject<Response>));

I solved this problem to add a public setter for all properties, which should be deserialized.


You could use the nuget package Newtonsoft.JSON in order to achieve this:

JsonConvert.DeserializeObject<List<Response>>(yourJsonString)

If you use C# 2010 or newer, you can use dynamic type:

dynamic json = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonstring);

Then you can access attributes and arrays in dynamic object using dot notation:

string nemo = json.response[0].images[0].report.nemo;

I had a scenario, and this one helped me

JObject objParserd = JObject.Parse(jsonString);

JObject arrayObject1 = (JObject)objParserd["d"];

D myOutput= JsonConvert.DeserializeObject<D>(arrayObject1.ToString());


shareInfo is Class:

public class ShareInfo
        {
            [JsonIgnore]
            public readonly DateTime Timestamp = DateTime.Now;
            [JsonProperty("sharename")]
            public string ShareName = null;
            [JsonProperty("readystate")]
            public string ReadyState = null;
            [JsonProperty("created")]
            [JsonConverter(typeof(Newtonsoft.Json.Converters.UnixDateTimeConverter))]
            public DateTime? CreatedUtc = null;
            [JsonProperty("title")]
            public string Title = null;
            [JsonProperty("getturl")]
            public string GettUrl = null;
            [JsonProperty("userid")]
            public string UserId = null;
            [JsonProperty("fullname")]
            public string Fullname = null;
            [JsonProperty("files")]
            public GettFile.FileInfo[] Files = new GettFile.FileInfo[0];
        }

// POST request.
            var gett = new WebClient { Encoding = Encoding.UTF8 };
            gett.Headers.Add("Content-Type", "application/json");
            byte[] request = Encoding.UTF8.GetBytes(jsonArgument.ToString());
            byte[] response = gett.UploadData(baseUri.Uri, request);

            // Response.
            var shareInfo = JsonConvert.DeserializeObject<ShareInfo>(Encoding.UTF8.GetString(response));

First install newtonsoft.json package to Visual Studio using NuGet Package Manager then add the following code:

ClassName ObjectName = JsonConvert.DeserializeObject < ClassName > (jsonObject);

Should just be this:

var jobject = JsonConvert.DeserializeObject<RootObject>(jsonstring);

You can paste the json string to here: http://json2csharp.com/ to check your classes are correct.


 public static void Main(string[] args)
{
    string json = @" {
    ""children"": [
            {
        ""url"": ""foo.pdf"", 
                ""expanded"": false, 
                ""label"": ""E14288-Passive-40085-2014_09_26.pdf"", 
                ""last_modified"": ""2014-09-28T11:19:49.000Z"", 
                ""type"": 1, 
                ""size"": 60929
            }
        ]
     }";




    var result = JsonConvert.DeserializeObject<ChildrenRootObject>(json);
    DataTable tbl = DataTableFromObject(result.children);
}

public static DataTable DataTableFromObject<T>(IList<T> list)
{
    DataTable tbl = new DataTable();
    tbl.TableName = typeof(T).Name;

    var propertyInfos = typeof(T).GetProperties();
    List<string> columnNames = new List<string>();

    foreach (PropertyInfo propertyInfo in propertyInfos)
    {
        tbl.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
        columnNames.Add(propertyInfo.Name);
    }

    foreach(var item in list)
    {
        DataRow row = tbl.NewRow();
        foreach (var name in columnNames)
        {
            row[name] = item.GetType().GetProperty(name).GetValue(item, null);
        }

        tbl.Rows.Add(row);
    }

    return tbl;
}

public class Child
{
    public string url { get; set; }
    public bool expanded { get; set; }
    public string label { get; set; }
    public DateTime last_modified { get; set; }
    public int type { get; set; }
    public int size { get; set; }
}

public class ChildrenRootObject
{
    public List<Child> children { get; set; }
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to deserialization

JSON to TypeScript class instance? Converting Stream to String and back...what are we missing? Newtonsoft JSON Deserialize Deserialize a JSON array in C# How do I deserialize a complex JSON object in C# .NET? .NET NewtonSoft JSON deserialize map to a different property name jackson deserialization json to java-objects Convert string with commas to array NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface> Right way to write JSON deserializer in Spring or extend it