Assaf Zigdon
Assaf Zigdon

Reputation: 461

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?

Upvotes: 40

Views: 191972

Answers (12)

Liviu Preda
Liviu Preda

Reputation: 1

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

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

Upvotes: 0

davidthegrey
davidthegrey

Reputation: 1483

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#.

Upvotes: 2

Tejas Jain
Tejas Jain

Reputation: 162

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

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

Upvotes: 9

Mahdi ghafoorian
Mahdi ghafoorian

Reputation: 1215

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>));

Upvotes: 1

everydayXpert
everydayXpert

Reputation: 857

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

Upvotes: 1

user6845177
user6845177

Reputation:

 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; }
}

Upvotes: 3

Veera Induvasi
Veera Induvasi

Reputation: 822

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));

Upvotes: 4

Ozesh
Ozesh

Reputation: 6994

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());

Upvotes: 4

Javal Patel
Javal Patel

Reputation: 838

I am using like this in my code and it's working fine

below is a piece of code which you need to write

using System.Web.Script.Serialization;

JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

Upvotes: 48

Uzzy
Uzzy

Reputation: 550

I am using following:

    using System.Web.Script.Serialization;       

    ...

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

Upvotes: 1

filipko
filipko

Reputation: 965

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;

Upvotes: 21

stevepkr84
stevepkr84

Reputation: 1657

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.

Upvotes: 45

Related Questions