【问题标题】:Issues Deserializing JSON反序列化 JSON 的问题
【发布时间】:2018-06-23 00:24:39
【问题描述】:

我正在尝试使用 newtonsoft.json 反序列化从 White Pages Pro api 返回的 json 字符串。一切都完美无缺并且完美反序列化,直到我进入 is_commercial。过去的一切都是我遇到问题的地方。我遇到的错误如下:

WhitePagesTool.jsonPersonComplex' 不包含“名称”的定义,并且找不到接受“WhitePagesTool.jsonPersonComplex”类型的第一个参数的扩展方法“名称”(您是否缺少 using 指令或程序集引用?)

下面抛出的所有错误

对于以下所有内容也会引发相同的错误: 名字、中间名、姓氏、年龄范围、性别、street_line_1、street_line_2、city、postal_code、state_code、country_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; }
        }

    }

}

这是我的整个表单编码

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

    }
}

这是我将使用的典型 JSON 字符串

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

  ]
}

【问题讨论】:

  • jsonPersonComplex 没有 有一个 name 属性。所有这些名称道具都在 BelongsTo 类中。请阅读How to Ask 并使用tour
  • 也许你的问题可以更详细一点。现在它太笼统了。
  • 欢迎来到 SO。请结束游览。有效的 SO 问题。审查结束(分类)。尽情享受吧 ;-)

标签: c# json serialization json.net


【解决方案1】:

您的“姓名”属性不在“jsonPersonComplex”类中,而是在“BelongsTo”类中。

debugOutput("Name:  " + jPerson.name);  //should be
debugOutput("Name:  " + jPerson.belongs_to().FirstOrDefault()?.name); //sorta like this for example.

您的命名约定也已关闭。 Newtonsoft 将自动为您将名称大写,尽管小写应该可以工作,我建议使用 c# 标准制作 c# 版本。 Newtonsoft 会转换以下标准,所以没关系。

我试过了,效果很好

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

        //Current_addresses added to address comments below.
        public List<CurrentAddress> Current_addresses { 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; }
    }
}

然后在逻辑中...

var jPerson = JsonConvert.DeserializeObject<JsonPersonComplex>(jsonString);  

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.Belongs_to.FirstOrDefault().Name); //and so on

//Street_line_1 added to address comments below
debugOutput("Name:  " + jPerson.Belongs_to.FirstOrDefault().Street_line_1); //and so on

【讨论】:

  • 感谢十亿!我知道我不应该在几年前就停止编码并继续使用不同的语言。一切都如此不同,当我在多年前编写代码时,Visual Basic 6.0 又回来了,我可以数数。再次感谢,这就像一个魅力,帮助我找出我在以后的构建中遇到的另一个问题!
  • 这工作完美无瑕...但是,任何从 CurrentAddress 类反序列化任何内容的尝试都会引发错误并挂起反序列化,如“我们遇到问题:值不能为空。参数名称:来源”它以 Street_line_1 开头,尽管该值不为空。该区域中没有任何内容是空的。返回空值的任何其他区域也不会挂起,它只是将其留空。
  • @KhaosBringer 您如何尝试打印 CurrentAddresses,因为请记住 CurrentAddresses 也是 Json 中的一个数组。这意味着您必须像我对 Belongs_to 的 linq 所做的那样在数组中查看。首先,您需要将 CurrentAddresses 添加到原始 JsonPersonComplexClass... public List&lt;CurrentAddress&gt; Current_addresses { get; set; } 然后您必须像使用 Belongs_to debugOutput("Name: " + jPerson.Belongs_to.FirstOrDefault().Street_line_1); //and so on 一样在 bebug 中编写它
  • @KhaosBringer 请查看我在此评论上方的评论,并注意我已更新答案,将您的 Current_address 包含在 cmets 中。您需要遵循此例程来完成其他对象的代码。我只是简单地回答了最低限度以节省空间,您添加其余部分将是一种很好的做法并帮助您理解。如果您需要更多帮助,我很乐意提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多