CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jan 2018
    Posts
    1

    Angry Issues Deserializing JSON String

    I appologize in advance as this is probably an easy fix, and going to be overly annoying for all who read it. However thanks in advance for ANY and ALL help given! I haven't coded in years, however recent events require me to pick back up again. I've never coded in anything except VB6, so this is all a learning process to me. I'm trying to use newtonsoft.json to deserialize a json string returned from White Pages Pro api. Everything worked perfectly and deserialized flawlessly UNTIL i got to is_commercial. Everything past there is where I run into issues with. The errors I'm encountering are as follows:

    WhitePagesTool.jsonPersonComplex' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'WhitePagesTool.jsonPersonComplex' could be found (are you missing a using directive or an assembly reference?)
    Also throws the same error for all the following:
    firstname, middlename, lastname, age_range, gender, street_line_1, street_line_2, city, postal_code, state_code, country_code, latitude, longitude, accuracy, and associated_people
    This is my Deserialization Class

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    
    namespace WhitePagesTool
    {
        class jsonPersonComplex
        {
            public string id { get; set; }
            public string phone_number { get; set; }
            public bool is_valid { get; set; }
            public string line_type { get; set; }
            public string carrier { get; set; }
            public bool is_prepaid { get; set; }
            public bool is_commercial { get; set; }
            public List<BelongsTo> belongs_to { get; set; }
    
    
            public class BelongsTo
            {
                public string name { get; set; }
                public string firstname { get; set; }
                public string middlename { get; set; }
                public string lastname { get; set; }
                public string age_range { get; set; }
                public string gender { get; set; }
                public string type { get; set; }
    
            }
            public class CurrentAddress
            {
                public string street_line_1 { get; set; }
                public object street_line_2 { get; set; }
                public string city { get; set; }
                public string postal_code { get; set; }
                public string state_code { get; set; }
                public string country_code { get; set; }
                public LatLong lat_long { get; set; }
            }
    
            public class LatLong
            {
                public double latitude { get; set; }
                public double longitude { get; set; }
                public string accuracy { get; set; }
            }
    
            public class AssociatedPeople
            {
                public string name { get; set; }
                public string firstname { get; set; }
                public string middlename { get; set; }
                public string lastname { get; set; }
                public string relation { get; set; }
            }
    
        }
    
    }
    Here's my Entire Form coding
    Code:
    using System;
    using Newtonsoft.Json;
    using System.Windows.Forms;
    
    namespace WhitePagesTool
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
    
            }
    
            #region UI events
    
            private void cmdDeserialize_Click(object sender, EventArgs e)
            {            
                deserialiseJSON(txtInput.Text);
            }
    
            private void cmdClear_Click(object sender, EventArgs e)
            {
                txtDebugOutput.Text = string.Empty;
            }
    
            #endregion
    
            #region json functions
    
            private void deserialiseJSON(string strJSON)
            {
                try
                {
                    //var jPerson = JsonConvert.DeserializeObject<dynamic>(strJSON);                         
                    var jPerson = JsonConvert.DeserializeObject<jsonPersonComplex>(strJSON);
    
                    //debugOutput("Here's Our JSON Object: " + jPerson.ToString());
    
                    debugOutput("Phone ID: " + jPerson.id.ToString());
                    debugOutput("Phone Number: " + jPerson.phone_number.ToString());
                    debugOutput("Valid Number: " + jPerson.is_valid);
                    debugOutput("Line Type: " + jPerson.line_type);
                    debugOutput("Carrier: " + jPerson.carrier);
                    debugOutput("Prepaid: " + jPerson.is_prepaid);
                    debugOutput("Commercial: " + jPerson.is_commercial);
    
                    debugOutput("Name:  " + jPerson.name);
                    debugOutput("First Name:  " + jPerson.firstname);
                    debugOutput("Middle Name:  " + jPerson.middlename);
                    debugOutput("Last Name:  " + jPerson.lastname);
                    debugOutput("Age Range:  " + jPerson.age_range);
                    debugOutput("Gender:  " + jPerson.gender);
    
                    debugOutput("Address:  " + jPerson.street_line_1);
                    debugOutput("Extended Address:  " + jPerson.street_line_2);
                    debugOutput("City:  " + jPerson.city);
                    debugOutput("Postal Code:  " + jPerson.postal_code);
                    debugOutput("State:  " + jPerson.state_code);
                    debugOutput("Country:  " + jPerson.country_code);
                    debugOutput("Latitude:  " + jPerson.latitude);
                    debugOutput("Longitude:  " + jPerson.longitude);
                    debugOutput("Accuracy:  " + jPerson.accuracy);
    
                    debugOutput("Associate Name:  " + jPerson.associated_people.name);
                    debugOutput("Associate First Name:  " + jPerson.associated_people.firstname);
                    debugOutput("Associate Middle Name:  " + jPerson.associated_people.middlename);
                    debugOutput("Associate Last Name:  " + jPerson.associated_people.lastname);
                    debugOutput("Associate Relationship:  " + jPerson.associated_people.relationship);
    
                    debugOutput("Associate Name:  " + jPerson.associated_people.name);
                    debugOutput("Associate First Name:  " + jPerson.associated_people.firstname);
                    debugOutput("Associate Middle Name:  " + jPerson.associated_people.middlename);
                    debugOutput("Associate Last Name:  " + jPerson.associated_people.lastname);
                    debugOutput("Associate Relationship:  " + jPerson.associated_people.relationship);
    
    
                    debugOutput("Associate Name:  " + jPerson.associated_people.name);
                    debugOutput("Associate First Name:  " + jPerson.associated_people.firstname);
                    debugOutput("Associate Middle Name:  " + jPerson.associated_people.middlename);
                    debugOutput("Associate Last Name:  " + jPerson.associated_people.lastname);
                    debugOutput("Associate Relationship:  " + jPerson.associated_people.relationship);
    
    
                    debugOutput("Associate Name:  " + jPerson.associated_people.name);
                    debugOutput("Associate First Name:  " + jPerson.associated_people.firstname);
                    debugOutput("Associate Middle Name:  " + jPerson.associated_people.middlename);
                    debugOutput("Associate Last Name:  " + jPerson.associated_people.lastname);
                    debugOutput("Associate Relationship:  " + jPerson.associated_people.relationship);
    
    
                    debugOutput("Associate Name:  " + jPerson.associated_people.name);
                    debugOutput("Associate First Name:  " + jPerson.associated_people.firstname);
                    debugOutput("Associate Middle Name:  " + jPerson.associated_people.middlename);
                    debugOutput("Associate Last Name:  " + jPerson.associated_people.lastname);
                    debugOutput("Associate Relationship:  " + jPerson.associated_people.relationship);
    
    
                }
                catch(Exception ex)
                {
                    debugOutput("We Had A Problem: " + ex.Message.ToString());
                }
            }
    
    
    
            #endregion
    
            #region Debug Output
    
            private void debugOutput(string strDebugText)
            {
                try
                {
                    System.Diagnostics.Debug.Write(strDebugText + Environment.NewLine);
                    txtDebugOutput.Text = txtDebugOutput.Text + strDebugText + Environment.NewLine;
                    txtDebugOutput.SelectionStart = txtDebugOutput.TextLength;
                    txtDebugOutput.ScrollToCaret();
                }
                catch(Exception ex)
                {
                    System.Diagnostics.Debug.Write(ex.Message.ToString() + Environment.NewLine);
                }
            }
    
            #endregion
    
        }
    }
    Last but not least, This is the typical JSON String I'll be working with
    Code:
    {
      "id": "Phone.ID.Number",
      "phone_number": "5555555555",
      "is_valid": true,
      "country_calling_code": "1",
      "line_type": "Landline",
      "carrier": "Suddenlink Communications",
      "is_prepaid": false,
      "is_commercial": false,
      "belongs_to": [
        {
          "id": "Person.ID.Number",
          "name": "John Json Doe",
          "firstname": "John",
          "middlename": "Json",
          "lastname": "Doe",
          "age_range": "30+",
          "gender": "Male",
          "type": "Person",
          "link_to_phone_start_date": "2018-01-01"
        }
      ],
      "current_addresses": [
        {
          "id": "Location.ID.Number",
          "location_type": "Address",
          "street_line_1": "123 Annoying Street",
          "street_line_2": null,
          "city": "CSharp",
          "postal_code": "12345",
          "zip4": "1234",
          "state_code": "FL",
          "country_code": "US",
          "lat_long": {
            "latitude": 12.345678,
            "longitude": -12.345678,
            "accuracy": "RoofTop"
          },
          "is_active": true,
          "delivery_point": "SingleUnit",
          "link_to_person_start_date": "2018-01-01"
        }
      ],
      "historical_addresses": [
    
      ],
      "associated_people": [
        {
          "id": "Person.ID.Number",
          "name": "Jane Doe",
          "firstname": "Jane",
          "middlename": null,
          "lastname": "Doe",
          "relation": "Household"
        },
        {
          "id": "Person.ID.Number",
          "name": "John J Doe",
          "firstname": "John",
          "middlename": "J",
          "lastname": "Doe",
          "relation": "Household"
        },
        {
          "id": "Person.ID.Number",
          "name": "John Json Doe",
          "firstname": "John",
          "middlename": "Json",
          "lastname": "Doe",
          "relation": "PotentialOwner"
        },
        {
          "id": "Person.ID.Number",
          "name": "Jane J Doe",
          "firstname": "Jane",
          "middlename": "J",
          "lastname": "Doe",
          "relation": "PotentialOwner"
        },
        {
          "id": "Person.ID.Number",
          "name": "Jane Json Doe",
          "firstname": "Jane",
          "middlename": "Json",
          "lastname": "Doe",
          "relation": "PotentialOwner"
        }
      ],
      "alternate_phones": [
    
      ],
      "error": null,
      "warnings": [
    
      ]
    }

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Issues Deserializing JSON String

    A couple of things:
    1) Many folks use something like Resharper which essentially enforces .Net C# class and property naming conventions. In C#, class and property names are PascalCase. Typically JSON variables are camelCase (or other naming conventions). As such, it's usually a good idea to follow the naming conventions of the language you are coding in. Fortunately, you can use the JsonObjectAttribute and JsonProperty attributes to control the naming of the json (while still adhering to the .Net C# naming conventions).
    2) For arrays or lists (e.g. like List<BelongsTo>), you need to initialize the list in a constructor. This probably was why your original attempt failed.
    3) When working with serialization (either JSON or XML), it is often helpful to work the problem in reverse. So rather than trying to deserialize a json string into a class instance, instead create an instance of the class, serialize it and then look at the JSON string. Then adjust the properties (and Json attributes) as necessary until the json is correct.

    The code below took a portion of your sample code and renames the class and property names using Pascal naming convention (while retaining your original JSON naming). It creates a JsonPersonComplex object, adds a couple of BelongsTo items, and serializes it into a JSON string. Next it takes the JSON string and deserializes it back into a JsonPersonComplex. Note that the BelongsTo list property gets initialized in the JsonPersonComplex constructor.

    Put a breakpoint on the
    Code:
    var jPersonJson = JsonConvert.SerializeObject(o);
    line and step through the code. In the debugger look at the jPersonJson string after the above line has executed, then step over the next line and inspect the jPerson object.

    Note: You'll need to add additional list properties like current_addresses, historical_addresses, and so on to get the JSON you posted above to load completely.

    Code:
    using System;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    
    namespace CG.JsonSerializer
    { 
        [JsonObjectAttribute("jsonPersonComplex")]
        public class JsonPersonComplex
        {
            [JsonProperty("id")]
            public string Id { get; set; }
    
            [JsonProperty("phone_number")]
            public string PhoneNumber { get; set; }
            [JsonProperty("is_valid")]
            public bool IsValid { get; set; }
            [JsonProperty("line_type")]
            public string LineType { get; set; }
            [JsonProperty("carrier")]
            public string Carrier { get; set; }
            [JsonProperty("is_prepaid")]
            public bool IsPrepaid { get; set; }
            [JsonProperty("is_commercial")]
            public bool IsCommercial { get; set; }
            [JsonProperty("belongs_to")]
            public List<BelongsTo> BelongsTo { get; set; }
    
            public JsonPersonComplex()
            {
                BelongsTo = new List<BelongsTo>();
            }
        }
    
        public class BelongsTo
        {
            [JsonProperty("name")]
            public string Name { get; set; }
            [JsonProperty("firstname")]
            public string FirstName { get; set; }
            [JsonProperty("middlename")]
            public string MiddleName { get; set; }
            [JsonProperty("lastname")]
            public string LastName { get; set; }
            [JsonProperty("age_range")]
            public string AgeRange { get; set; }
            [JsonProperty("gender")]
            public string Gender { get; set; }
            [JsonProperty("type")]
            public string BelongsToType { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    var o = new JsonPersonComplex
                    {
                        Id = "125",
                        PhoneNumber = "235.469.4040",
                        IsValid = true,
                        LineType = "TypeA",
                        Carrier = "Sprint",
                        IsPrepaid = false,
                        IsCommercial = true
                    };
    
                    o.BelongsTo.Add(new BelongsTo
                    {
                        Name = "Huey B Lewis",
                        FirstName = "Huey",
                        MiddleName = "B",
                        LastName = "Lewis",
                        AgeRange = "20 - 35",
                        Gender = "Male",
                        BelongsToType = "BelongsToTypeA",
                    });
    
                    o.BelongsTo.Add(new BelongsTo
                    {
                        Name = "David L Bowie",
                        FirstName = "David",
                        MiddleName = "L",
                        LastName = "Bowie",
                        AgeRange = "30 - 55",
                        Gender = "Male",
                        BelongsToType = "BelongsToTypeB",
                    });
    
                    var jPersonJson = JsonConvert.SerializeObject(o);
    
                    var jPerson = JsonConvert.DeserializeObject<JsonPersonComplex>(jPersonJson);
                }
                catch (Exception e)
                {
    
                }
            }
        }
    }
    Last edited by Arjay; January 17th, 2018 at 01:04 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured