在C#中反序列化json的问题 [英] Issues deserializing json in C#

查看:98
本文介绍了在C#中反序列化json的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前道歉,因为这可能是一个简单的解决方案,对于所有阅读它的人来说都会过于烦人。但是,提前感谢任何和所有帮助!我没有多年编码,但最近的事件要求我再次回来。除了VB6之外,我从来没有编写任何代码,所以这对我来说都是一个学习过程。我正在尝试使用newtonsoft.json反序列化从White Pages Pro api返回的json字符串。一切都运作良好,并且完美无序地反序列化直到我的商业。过去的一切都是我遇到问题的地方。我遇到的错误如下:



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





同样会出现以下所有错误:

firstname,middlename,lastname,age_range,gender,street_line_1,street_line_2,city,postal_code,state_code,country_code,纬度,经度,准确度,和associated_people



这是我将要使用的典型Json字符串(由于显而易见的原因而更改了信息):



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 the typical Json string I'll be working with (changed info for obvious reasons):

{
  "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": [

  ]
}





这是我的反序列化课程





This is my Deserialize Class

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

    }

}





这是我的整个表格代码





This is my entire Form 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

    }
}





我尝试过:



我能想到的一切。我看过无数小时的视频,一切正常,直到我完成了一部分!



What I have tried:

Everything I Can think of. I've watched countless hours of videos, and everything works, UNTIL I get past the one part!

推荐答案

你的代码是:
debugOutput("Name:  " + jPerson.Name);

但是你的财产定义是:

public string name { get; set; }

这是 name 而不是 Name :C#标识符区分大小写。

So that's name rather than Name: C# identifiers are case-sensitive.


本文详细介绍了如何反序列化JSON以及可用于帮助您的工具:在C#中使用JSON& VB [ ^ ]



这是由 JSON Utils:Generate C#,VB生成的代码。来自JSON的网络,SQL表,Java和PHP [ ^ ]:

This article goes into detail on how to Deserialize JSON and the tools that you can use to help you: Working with JSON in C# & VB[^]

Here is the code generated by JSON Utils: Generate C#, VB.Net, SQL Table, Java and PHP from JSON[^]:
namespace WhitePagesTool
{
        public class BelongsTo
        {
            [JsonProperty("id")]
            public string Id { get; set; }

            [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 Type { get; set; }

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

        public class LatLong
        {
            [JsonProperty("latitude")]
            public double Latitude { get; set; }

            [JsonProperty("longitude")]
            public double Longitude { get; set; }

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

        public class CurrentAddress
        {
            [JsonProperty("id")]
            public string Id { get; set; }

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

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

            [JsonProperty("street_line_2")]
            public object StreetLine2 { get; set; }

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

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

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

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

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

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

            [JsonProperty("is_active")]
            public bool IsActive { get; set; }

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

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

        public class AssociatedPeople
        {
            [JsonProperty("id")]
            public string Id { get; set; }

            [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("relation")]
            public string Relation { get; set; }
        }

        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("country_calling_code")]
            public string CountryCallingCode { 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 IList<BelongsTo> BelongsTo { get; set; }

            [JsonProperty("current_addresses")]
            public IList<CurrentAddress> CurrentAddresses { get; set; }

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

            [JsonProperty("associated_people")]
            public IList<AssociatedPeople> AssociatedPeople { get; set; }

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

            [JsonProperty("error")]
            public object Error { get; set; }

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



The code generated maps the JSON property names to CamelCase C# properties. This should help reduce the confusion in your code.



UPDATE: Added support for nullable types.


The code generated maps the JSON property names to CamelCase C# properties. This should help reduce the confusion in your code.

UPDATE: Added support for nullable types.

namespace WhitePagesTool
{
	public class BelongsTo
	{
		[JsonProperty("id")]
		public string Id { get; set; }

		[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 Type { get; set; }

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

	public class LatLong
	{
		[JsonProperty("latitude")]
		public double? Latitude { get; set; }

		[JsonProperty("longitude")]
		public double? Longitude { get; set; }

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

	public class CurrentAddress
	{
		[JsonProperty("id")]
		public string Id { get; set; }

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

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

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

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

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

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

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

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

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

		[JsonProperty("is_active")]
		public bool? IsActive { get; set; }

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

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

	public class AssociatedPeople
	{
		[JsonProperty("id")]
		public string Id { get; set; }

		[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("relation")]
		public string Relation { get; set; }
	}

	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("country_calling_code")]
		public string CountryCallingCode { 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 IList<BelongsTo> BelongsTo { get; set; }

		[JsonProperty("current_addresses")]
		public IList<CurrentAddress> CurrentAddresses { get; set; }

		//[JsonProperty("historical_addresses")]
		//public IList<object> HistoricalAddresses { get; set; }

		[JsonProperty("associated_people")]
		public IList<AssociatedPeople> AssociatedPeople { get; set; }

		//[JsonProperty("alternate_phones")]
		//public IList<object> AlternatePhones { get; set; }

		//[JsonProperty("error")]
		//public object Error { get; set; }

		//[JsonProperty("warnings")]
		//public IList<object> Warnings { get; set; }
	}
}



NOTE: There are some properties where no JSON data was provided. I have commented these out to prevent errors. You will need to add them yourself.


NOTE: There are some properties where no JSON data was provided. I have commented these out to prevent errors. You will need to add them yourself.


这篇关于在C#中反序列化json的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆