Click here to Skip to main content
15,921,530 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:

I have a json:

{"envelope":{"headers":{"test.source":"source system", "":"test", "test.entity":"Plan", "test.revisionHistory":{"test.createdBy":"admin", "test.createTimeStamp":"2017-08-09T00:00:00", "test.updatedBy":"admin", "test.updatedTimeStamp":"2017-08-09T00:00:00"}, "test.identifiers":{"test.PlanId":"10000001"}}, "triples":[], "instance":{"PlanId":"10000001", "PlanName":"The Health Plan", "PlanType":"Discount Plan", "MailingState":"CA ", "MailingZipCode":"99999-1503", "MailingAddress":"Some Name LLP, 350 South Street Ave., 13th Floor", "MailingCity":"Los Angeles", "MonitoringExaminer":{"examinerName":"abc", "examinerEmail":"", "examinerPhone":"916-222-2222"}, "planContact":{"ContactName":"xyz", "ContactEmail":"", "eFileContactPhone":"916-111-1111"}, "testLicensingContact":{"licensingContactName":"xyz", "licensingContactEmail":"", "licensingContactPhone":"916-111-1111"}, "financialContact":{"financialContactName":"Jack Doe", "financialContactEmail":"", "financialContactPhone":"916-111-1111"}}, "attachments":null}}

UPDATE: Formatted version (using JSON Formatter & Validator[^]) for easier reading...
         "test.source":"source system",

         "PlanName":"The Health Plan",
         "PlanType":"Discount Plan",
         "MailingState":"CA ",
         "MailingAddress":"Some Name LLP, 350 South Street Ave., 13th Floor",
         "MailingCity":"Los Angeles",
            "financialContactName":"Jack Doe",

What I have tried:

Hi ,

How to convert JSON to object using deserializer ?
Updated 11-Aug-17 13:58pm

1 solution

First thing is to create a class structure to convert the JSON to. You can use
1. ‘Paste JSON As Classes’ Visual Studio Addin[^]; or
2. A webtool like JSON Utils[^]

#2 above is my personal favourite as you have greater control over the code generated. Pasting your JSON into that website tool generates the following class structure:
public class TestRevisionHistory
        public string TestCreatedBy { get; set; }

        public DateTime TestCreateTimeStamp { get; set; }

        public string TestUpdatedBy { get; set; }

        public DateTime TestUpdatedTimeStamp { get; set; }

    public class TestIdentifiers
        public string TestPlanId { get; set; }

    public class Headers
        public string TestSource { get; set; }

        public string TestAgency { get; set; }

        public string TestEntity { get; set; }

        public TestRevisionHistory TestRevisionHistory { get; set; }

        public TestIdentifiers TestIdentifiers { get; set; }

    public class MonitoringExaminer
        public string ExaminerName { get; set; }

        public string ExaminerEmail { get; set; }

        public string ExaminerPhone { get; set; }

    public class PlanContact
        public string ContactName { get; set; }

        public string ContactEmail { get; set; }

        public string EFileContactPhone { get; set; }

    public class TestLicensingContact
        public string LicensingContactName { get; set; }

        public string LicensingContactEmail { get; set; }

        public string LicensingContactPhone { get; set; }

    public class FinancialContact
        public string FinancialContactName { get; set; }

        public string FinancialContactEmail { get; set; }

        public string FinancialContactPhone { get; set; }

    public class Instance
        public string PlanId { get; set; }

        public string PlanName { get; set; }

        public string PlanType { get; set; }

        public string MailingState { get; set; }

        public string MailingZipCode { get; set; }

        public string MailingAddress { get; set; }

        public string MailingCity { get; set; }

        public MonitoringExaminer MonitoringExaminer { get; set; }

        public PlanContact PlanContact { get; set; }

        public TestLicensingContact TestLicensingContact { get; set; }

        public FinancialContact FinancialContact { get; set; }

    public class Envelope
        public Headers Headers { get; set; }

        public IList<object> Triples { get; set; }

        public Instance Instance { get; set; }

        public object Attachments { get; set; }

    public class Response
        public Envelope Envelope { get; set; }

Nest you need to map the raw JSON data to the class structure. Again, there are a few libraries out there:
1. Microsoft's own functions: How to: Serialize and Deserialize JSON Data | Microsoft Docs[^];
2. fastJSON[^]; or
3. Json.NET - Newtonsoft[^]

#3 is my personal favourite as it allows support for complex custom serialization. For this solution, I'll be using #3. You can add it to your project using NuGet: NuGet Gallery | Json.NET 10.0.3[^] and here is my helper class:
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;

Then to use with the above classes:
string rawJson = "{\"envelope\":{\"headers\":{\"test.source\":\"source system\", \"\":\"test\", \"test.entity\":\"Plan\", \"test.revisionHistory\":{\"test.createdBy\":\"admin\", \"test.createTimeStamp\":\"2017-08-09T00:00:00\", \"test.updatedBy\":\"admin\", \"test.updatedTimeStamp\":\"2017-08-09T00:00:00\"}, \"test.identifiers\":{\"test.PlanId\":\"10000001\"}}, \"triples\":[], \"instance\":{\"PlanId\":\"10000001\", \"PlanName\":\"The Health Plan\", \"PlanType\":\"Discount Plan\", \"MailingState\":\"CA \", \"MailingZipCode\":\"99999-1503\", \"MailingAddress\":\"Some Name LLP, 350 South Street Ave., 13th Floor\", \"MailingCity\":\"Los Angeles\", \"MonitoringExaminer\":{\"examinerName\":\"abc\", \"examinerEmail\":\"\", \"examinerPhone\":\"916-222-2222\"}, \"planContact\":{\"ContactName\":\"xyz\", \"ContactEmail\":\"\", \"eFileContactPhone\":\"916-111-1111\"}, \"testLicensingContact\":{\"licensingContactName\":\"xyz\", \"licensingContactEmail\":\"\", \"licensingContactPhone\":\"916-111-1111\"}, \"financialContact\":{\"financialContactName\":\"Jack Doe\", \"financialContactEmail\":\"\", \"financialContactPhone\":\"916-111-1111\"}}, \"attachments\":null}}";

var result = JsonConverter.ToClass<Response>(rawJson);
Share this answer
AlwzLearning 12-Aug-17 22:21pm    
Thank you so much for the beautiful answer. I knew I was not creating class structure correctly. Your JSONConverted class is awesome. Thank You again.

While I was trying to understand , I had few questions like :

1. what would be JSON settings ? can you give some example like what settings can be set and how they are useful
2. While using tool , is there a chance we can miss some property if it is null.
3. I am trying to set up a Project using MVC and want your advise for same : The project I am working on is all about consuming apis' and I would like to know what is the best practice for where to keep apis .. shall I keep it as a different project and refer that project in mvc or I can keep in same project as mvc
Graeme_Grant 12-Aug-17 22:52pm    
You are most welcome. I am writing a CodeProject article at the moment that will go into a lot more detail. But for now:
1. Serialization Settings[^]
2. It depends on you class structure for deserialization - the above JSON data has the "triples" object empty, so the class type is unknown and set as an object - you can either fix this by using the tool mentioned with a new set of data including a "triples" or manually create the class(es) yourself. For Serialization, if you don't want to serialize a field, simply use the [JsonIgnore] attribute[^]. "Serialization Settings" also has some other choices for you, however, I have never needed to use them - default settings work fine.
3. I keep all my "API Service" libraries and classes in a separate library and add a reference to the project that I am working on. Keeps it clean and reusable for other projects.

Hope this helps! :)
AlwzLearning 13-Aug-17 3:42am    
Thank You
AlwzLearning 13-Aug-17 13:25pm    
Hi Graeme_Grant, I again need your help. The class "Response" to which the json was mapped , I am trying to bind that class to view in MVC but it is not setting the values.
Am I not supposed to use the same class as model in view ? How should I map those results to the view.
Thank You :)
AlwzLearning 13-Aug-17 13:45pm    
Never mind. I was binding it wrongly. I was able to bind it successfully.
Thank you

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