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

I have a json:

{"envelope":{"headers":{"test.source":"source system", "test.agency":"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":"abc@test.ca.gov", "examinerPhone":"916-222-2222"}, "planContact":{"ContactName":"xyz", "ContactEmail":"xyz@Plan.com", "eFileContactPhone":"916-111-1111"}, "testLicensingContact":{"licensingContactName":"xyz", "licensingContactEmail":"xyz@test.ca.gov", "licensingContactPhone":"916-111-1111"}, "financialContact":{"financialContactName":"Jack Doe", "financialContactEmail":"xyz@Plan.com", "financialContactPhone":"916-111-1111"}}, "attachments":null}}


UPDATE: Formatted version (using JSON Formatter & Validator[^]) for easier reading...
{
   "envelope":{
      "headers":{
         "test.source":"source system",
         "test.agency":"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":"abc@test.ca.gov",
            "examinerPhone":"916-222-2222"
         },
         "planContact":{
            "ContactName":"xyz",
            "ContactEmail":"xyz@Plan.com",
            "eFileContactPhone":"916-111-1111"
         },
         "testLicensingContact":{
            "licensingContactName":"xyz",
            "licensingContactEmail":"xyz@test.ca.gov",
            "licensingContactPhone":"916-111-1111"
         },
         "financialContact":{
            "financialContactName":"Jack Doe",
            "financialContactEmail":"xyz@Plan.com",
            "financialContactPhone":"916-111-1111"
         }
      },
      "attachments":null
   }
}


What I have tried:

Hi ,

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

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:
C#
public class TestRevisionHistory
    {
        [JsonProperty("test.createdBy")]
        public string TestCreatedBy { get; set; }

        [JsonProperty("test.createTimeStamp")]
        public DateTime TestCreateTimeStamp { get; set; }

        [JsonProperty("test.updatedBy")]
        public string TestUpdatedBy { get; set; }

        [JsonProperty("test.updatedTimeStamp")]
        public DateTime TestUpdatedTimeStamp { get; set; }
    }

    public class TestIdentifiers
    {
        [JsonProperty("test.PlanId")]
        public string TestPlanId { get; set; }
    }

    public class Headers
    {
        [JsonProperty("test.source")]
        public string TestSource { get; set; }

        [JsonProperty("test.agency")]
        public string TestAgency { get; set; }

        [JsonProperty("test.entity")]
        public string TestEntity { get; set; }

        [JsonProperty("test.revisionHistory")]
        public TestRevisionHistory TestRevisionHistory { get; set; }

        [JsonProperty("test.identifiers")]
        public TestIdentifiers TestIdentifiers { get; set; }
    }

    public class MonitoringExaminer
    {
        [JsonProperty("examinerName")]
        public string ExaminerName { get; set; }

        [JsonProperty("examinerEmail")]
        public string ExaminerEmail { get; set; }

        [JsonProperty("examinerPhone")]
        public string ExaminerPhone { get; set; }
    }

    public class PlanContact
    {
        [JsonProperty("ContactName")]
        public string ContactName { get; set; }

        [JsonProperty("ContactEmail")]
        public string ContactEmail { get; set; }

        [JsonProperty("eFileContactPhone")]
        public string EFileContactPhone { get; set; }
    }

    public class TestLicensingContact
    {
        [JsonProperty("licensingContactName")]
        public string LicensingContactName { get; set; }

        [JsonProperty("licensingContactEmail")]
        public string LicensingContactEmail { get; set; }

        [JsonProperty("licensingContactPhone")]
        public string LicensingContactPhone { get; set; }
    }

    public class FinancialContact
    {
        [JsonProperty("financialContactName")]
        public string FinancialContactName { get; set; }

        [JsonProperty("financialContactEmail")]
        public string FinancialContactEmail { get; set; }

        [JsonProperty("financialContactPhone")]
        public string FinancialContactPhone { get; set; }
    }

    public class Instance
    {
        [JsonProperty("PlanId")]
        public string PlanId { get; set; }

        [JsonProperty("PlanName")]
        public string PlanName { get; set; }

        [JsonProperty("PlanType")]
        public string PlanType { get; set; }

        [JsonProperty("MailingState")]
        public string MailingState { get; set; }

        [JsonProperty("MailingZipCode")]
        public string MailingZipCode { get; set; }

        [JsonProperty("MailingAddress")]
        public string MailingAddress { get; set; }

        [JsonProperty("MailingCity")]
        public string MailingCity { get; set; }

        [JsonProperty("MonitoringExaminer")]
        public MonitoringExaminer MonitoringExaminer { get; set; }

        [JsonProperty("planContact")]
        public PlanContact PlanContact { get; set; }

        [JsonProperty("testLicensingContact")]
        public TestLicensingContact TestLicensingContact { get; set; }

        [JsonProperty("financialContact")]
        public FinancialContact FinancialContact { get; set; }
    }

    public class Envelope
    {
        [JsonProperty("headers")]
        public Headers Headers { get; set; }

        [JsonProperty("triples")]
        public IList<object> Triples { get; set; }

        [JsonProperty("instance")]
        public Instance Instance { get; set; }

        [JsonProperty("attachments")]
        public object Attachments { get; set; }
    }

    public class Response
    {
        [JsonProperty("envelope")]
        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:
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;
    }
}

Then to use with the above classes:
C#
string rawJson = "{\"envelope\":{\"headers\":{\"test.source\":\"source system\", \"test.agency\":\"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\":\"abc@test.ca.gov\", \"examinerPhone\":\"916-222-2222\"}, \"planContact\":{\"ContactName\":\"xyz\", \"ContactEmail\":\"xyz@Plan.com\", \"eFileContactPhone\":\"916-111-1111\"}, \"testLicensingContact\":{\"licensingContactName\":\"xyz\", \"licensingContactEmail\":\"xyz@test.ca.gov\", \"licensingContactPhone\":\"916-111-1111\"}, \"financialContact\":{\"financialContactName\":\"Jack Doe\", \"financialContactEmail\":\"xyz@Plan.com\", \"financialContactPhone\":\"916-111-1111\"}}, \"attachments\":null}}";

var result = JsonConverter.ToClass<Response>(rawJson);
 
Share this answer
 
v3
Comments
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