JSON返回空值时的错误 [英] Errors when JSON returns a null value

查看:113
本文介绍了JSON返回空值时的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我最近再次开始编码,到目前为止,这个论坛对我来说更有帮助。无论如何,我正在研究一个简单的表单,它从Web API中获取JSON字符串并将其反序列化为一个列表框。但是,任何返回任何空值错误的字符串。我知道这是一个简单的问题,但不能为我的生活弄清楚如何让它忽略空值!提前致谢!



我尝试过:



这是我的第一站求助

So I recently started coding again, and this forum has been MORE then helpful to me thus far. Anyways, I'm working on a simple form that snags a JSON String from a Web API and Deserializes it into a list box. However, any string that returns ANY null value errors out. I know this is a simple issue, but can't for the life of me figure out how to get it to ignore the null values! Thanks in advance!

What I have tried:

This is my first stop for help

推荐答案

问题是你没有正确地将JSON属性映射到C#类属性。这就是你收到错误的原因。


请看在C#中反序列化json的问题 - 解决方案1 ​​ [ ^ ]正确映射它们。
The problem is that you're not mapping the JSON properties to the C# class properties correctly. This is why you are getting the error.

Please look at Issues deserializing json in C# - Solution 1[^] to correctly map them.


表格代码



Form Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;


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<JsonPersonComplex>(strJSON);
                

                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); 
                debugOutput("First Name: " + jPerson.Belongs_to.FirstOrDefault().Firstname);
                debugOutput("Middle Name: " + jPerson.Belongs_to.FirstOrDefault().Middlename);
                debugOutput("Last Name: " + jPerson.Belongs_to.FirstOrDefault().Lastname);
                debugOutput("Age Range: " + jPerson.Belongs_to.FirstOrDefault().Age_range);
                debugOutput("Gender: " + jPerson.Belongs_to.FirstOrDefault().Gender);
                debugOutput("Type: " + jPerson.Belongs_to.FirstOrDefault().Type);

                
                debugOutput("Street Address: " + jPerson.Current_address.FirstOrDefault().Street_line_1);              
                debugOutput("Extended Address: " + jPerson.Current_address.FirstOrDefault().Street_line_2);
                debugOutput("City: " + jPerson.Current_address.FirstOrDefault().City);
                debugOutput("Zip Code: " + jPerson.Current_address.FirstOrDefault().Postal_code);
                debugOutput("State: " + jPerson.Current_address.FirstOrDefault().State_code);
                debugOutput("Country: " + jPerson.Current_address.FirstOrDefault().Country_code);


                

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







反序列化课程






Deserialize Class

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 List<CurrentAddress> Current_address { get; set; }
        public List<LatLong> Lat_long { get; set; }
        public List<AssociatedPeople> Associated_people { 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; }
    }
}







最后是JSON字符串我是使用






And Finally The JSON String I'm Working With

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

  ]
}


这篇关于JSON返回空值时的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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