Click here to Skip to main content
15,072,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
I am facing a problem with json deserialization in c# class. The Json will return by api is :-
JavaScript
{
    "fields": [
        {
            "value": "3732",
            "order": 1,
            "name": "id",
            "type": "hidden"
        },
        {
            "maxlen": "13",
            "required": "",
            "value": "0",
            "order": 2,
            "name": "job",
            "label": "Job ",
            "type": "text"
        },
        {
            "maxlen": "13",
            "required": "",
            "value": "0",
            "order": 3,
            "name": "client",
            "label": "Client ",
            "type": "text"
        },
        {
            "maxlen": "50",
            "required": "required",
            "value": "Tim Nguyen",
            "order": 4,
            "name": "task_name",
            "label": "Task Name ",
            "type": "text"
        },
        {
            "required": "required",
            "time": "05:30 PM",
            "date": "07/18/2017",
            "order": 5,
            "name": "start_date",
            "label": "Start Date ",
            "type": "datetime"
        },
        {
            "required": "",
            "time": "07:00 PM",
            "date": "07/18/2017",
            "order": 6,
            "name": "end_date",
            "label": "End Date ",
            "type": "datetime"
        },
        {
            "required": "",
            "value": "Roof Inspection",
            "order": 7,
            "name": "task_description",
            "label": "Task Description ",
            "type": "textareainput"
        }
    ],
    "action": "update_task",
    "hidden": {},
    "display": "Update Task"
}


Please help me to solve this.

Regard
Ankush

What I have tried:

C#
public class FormFillByTaskId
{
	public FieldData[] fields { get; set; }
}
public class FieldData
{
   // Don't know how to deserialize over here..
}
Posted
Updated 28-Jul-17 0:46am
v2
Comments
F-ES Sitecore 28-Jul-17 6:48am
   
Google "c# deserialise json" - this is very well documented, lots of examples if you just search
Graeme_Grant 28-Jul-17 6:50am
   
Or check out the solution below... ;)
F-ES Sitecore 28-Jul-17 6:59am
   
Give a man a fish....
Graeme_Grant 15-Aug-17 23:27pm
   
Why only a single fish when I can give a bucket full! ;)

Working with JSON in C# & VB[^]

1 solution

There are websites that will generate classes for you from JSON data. My favourite is: JSON Utils: Generate C#, VB.Net, SQL Table, Java and PHP from JSON[^]

Using the above JSON data, the following classes are generated:
C#
public class Field
{

    [JsonProperty("value")]
    public string Value { getset; }

    [JsonProperty("order")]
    public int Order { getset; }

    [JsonProperty("name")]
    public string Name { getset; }

    [JsonProperty("type")]
    public string Type { getset; }

    [JsonProperty("maxlen")]
    public string Maxlen { getset; }

    [JsonProperty("required")]
    public string Required { getset; }

    [JsonProperty("label")]
    public string Label { getset; }

    [JsonProperty("time")]
    public string Time { getset; }

    [JsonProperty("date")]
    public string Date { getset; }
}

public class Hidden
{
}

public class Example
{

    [JsonProperty("fields")]
    public IList<Field> Fields { getset; }

    [JsonProperty("action")]
    public string Action { getset; }

    [JsonProperty("hidden")]
    public Hidden Hidden { getset; }

    [JsonProperty("display")]
    public string Display { getset; }
}

Next you will need to write code to convert / map the JSON data to the class structure. NuGet Gallery | Json.NET 10.0.3[^] is used by most.

Once referenced in your project, here is a helper class that I use to do the conversion from/to classes:
C#
public static class JsonConverter
{
    public static string FromClass<T>(T data, bool isEmptyToNull = false, JsonSerializerSettings jsonSettings = null)
    {
        string response = string.Empty;

        if (!EqualityComparer<T>.Default.Equals(data, default(T)))
            response = JsonConvert.SerializeObject(data, jsonSettings);

        return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
    }

    public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
    {
        var response = default(T);

        if (!string.IsNullOrEmpty(data))
            response = jsonSettings == null
                ? JsonConvert.DeserializeObject<T>(data)
                : JsonConvert.DeserializeObject<T>(data, jsonSettings);

        return response;
    }
}

And this is how to use the helper class:
C#
var rawJson = "{\"fields\": [{\"value\": \"3732\",\"order\": 1,\"name\": \"id\",\"type\": \"hidden\"},{\"maxlen\": \"13\",\"required\": \"\",\"value\": \"0\",\"order\": 2,\"name\": \"job\",\"label\": \"Job \",\"type\": \"text\"},{\"maxlen\": \"13\",\"required\": \"\",\"value\": \"0\",\"order\": 3,\"name\": \"client\",\"label\": \"Client \",\"type\": \"text\"},{\"maxlen\": \"50\",\"required\": \"required\",\"value\": \"Tim Nguyen\",\"order\": 4,\"name\": \"task_name\",\"label\": \"Task Name \",\"type\": \"text\"},{\"required\": \"required\",\"time\": \"05:30 PM\",\"date\": \"07/18/2017\",\"order\": 5,\"name\": \"start_date\",\"label\": \"Start Date \",\"type\": \"datetime\"},{\"required\": \"\",\"time\": \"07:00 PM\",\"date\": \"07/18/2017\",\"order\": 6,\"name\": \"end_date\",\"label\": \"End Date \",\"type\": \"datetime\"},{\"required\": \"\",\"value\": \"Roof Inspection\",\"order\": 7,\"name\": \"task_description\",\"label\": \"Task Description \",\"type\": \"textareainput\"}],\"action\": \"update_task\",\"hidden\": {},\"display\": \"Update Task\"}";
var result = JsonConverter.ToClass<Example>(rawJson);
   
Comments
BillWoodruff 28-Jul-17 13:30pm
   
+5 Very useful information !

I'd like to suggest you write an article about your work with Newtonsoft flavor JSON.

Also, I'd like to encourage ypu to think about whether QA is a service to write code for other people, or a forum to help other people learn to become better programmers who can, possibly, solve a wider range of problems for themselves. Admittedly, those two "roles" (teacher, provider) are not always able to be separated out.

with respect for your intellect, productivity, and your fine contributions, Bill
Graeme_Grant 28-Jul-17 18:19pm
   
Thanks, Bill, much appreciated. Above looks like a lot of work but actually only took me a minute or two - mainly copy and paste. ;)

I have thought about writing a few articles, just haven't found the time. But after your feedback, I'll see if I can find some time... ;)
Graeme_Grant 15-Aug-17 23:26pm
   
I've found the time Bill and have published an article... Working with JSON in C# & VB[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900