Object reference error while reading specific JSON string?

醉酒当歌 提交于 2019-12-31 05:48:06

问题


I have used JSON to C# Class Converter and it generates the following Class:

JSON

{"ios_info":{"serialNumber":"F2LLMBNJFFF","imeiNumber":"01388400413235","meid":"","iccID":"8901410427640096045","firstUnbrickDate":"11\/27\/13","lastUnbrickDate":"11\/27\/13","unbricked":"true","unlocked":"false","productVersion":"7.1.2","initialActivationPolicyID":"23","initialActivationPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","appliedActivationPolicyID":"23","appliedActivationDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","nextTetherPolicyID":"23","nextTetherPolicyDetails":"US AT&T Puerto Rico and US Virgin Islands Activation Policy","macAddress":"ACFDEC6C988A","bluetoothMacAddress":"AC:FD:EC:6C:98:8B","partDescription":"IPHONE 5S SPACE GRAY 64GB-USA"},"fmi":{"@attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"@attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},"product_info":{"serialNumber":"F2LLMBNJFFF","warrantyStatus":"Apple Limited Warranty","coverageEndDate":"11\/25\/14","coverageStartDate":"11\/26\/13","daysRemaining":"497","estimatedPurchaseDate":"11\/26\/13","purchaseCountry":"United States","registrationDate":"11\/26\/13","imageURL":"http:\/\/service.info.apple.com\/parts\/service_parts\/na.gif","explodedViewURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","manualURL":"http:\/\/service.info.apple.com\/manuals-ssol.html","productDescription":"iPhone 5S","configDescription":"IPHONE 5S GRAY 64GB GSM","slaGroupDescription":"","contractCoverageEndDate":"11\/25\/15","contractCoverageStartDate":"11\/26\/13","contractType":"C1","laborCovered":"Y","limitedWarranty":"Y","partCovered":"Y","notes":"Covered by AppleCare+ - Incidents Available","acPlusFlag":"Y","consumerLawInfo":{"serviceType":"","popMandatory":"","allowedPartType":""}}}

From Above JSON all the data is read but only the line at which i get error is in reading the JSON is:

fmi":{"@attributes":{"version":"1","deviceCount":"1"},"fmipLockStatusDevice":{"@attributes":{"serial":"F2LLMBNJFFFQ","imei":"013884004132355","isLocked":"true","isLost":"false"}}},

Error:

Object Reference not set to an instance of object.

public class AppleAPI
{
    public IosInfo ios_info { get; set; }
    public ProductInfo product_info { get; set; }
    public Fmi fmi { get; set; }
    public class IosInfo
    {
        public string serialNumber { get; set; }
        public string imeiNumber { get; set; }
        public string meid { get; set; }
        public string iccID { get; set; }
        public string firstUnbrickDate { get; set; }
        public string lastUnbrickDate { get; set; }
        public string unbricked { get; set; }
        public string unlocked { get; set; }
        public string productVersion { get; set; }
        public string initialActivationPolicyID { get; set; }
        public string initialActivationPolicyDetails { get; set; }
        public string appliedActivationPolicyID { get; set; }
        public string appliedActivationDetails { get; set; }
        public string nextTetherPolicyID { get; set; }
        public string nextTetherPolicyDetails { get; set; }
        public string macAddress { get; set; }
        public string bluetoothMacAddress { get; set; }
        public string partDescription { get; set; }
    }

    public class ConsumerLawInfo
    {
        public string serviceType { get; set; }
        public string popMandatory { get; set; }
        public string allowedPartType { get; set; }
    }


    public class ProductInfo
    {
        public string serialNumber { get; set; }
        public string warrantyStatus { get; set; }
        public string coverageEndDate { get; set; }
        public string coverageStartDate { get; set; }
        public string daysRemaining { get; set; }
        public string estimatedPurchaseDate { get; set; }
        public string purchaseCountry { get; set; }
        public string registrationDate { get; set; }
        public string imageURL { get; set; }
        public string explodedViewURL { get; set; }
        public string manualURL { get; set; }
        public string productDescription { get; set; }
        public string configDescription { get; set; }
        public string slaGroupDescription { get; set; }
        public string contractCoverageEndDate { get; set; }
        public string contractCoverageStartDate { get; set; }
        public string contractType { get; set; }
        public string laborCovered { get; set; }
        public string limitedWarranty { get; set; }
        public string partCovered { get; set; }
        public string notes { get; set; }
        public string acPlusFlag { get; set; }
        public ConsumerLawInfo consumerLawInfo { get; set; }
    }

    public class Fmi
    {
        public Attributes invalid_nameattribute { get; set; }
        public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
    }
    public class FmipLockStatusDevice
    {
        public Attributes2 invalid_nameattribute2 { get; set; }
    }
    public class Attributes
    {
        public string version { get; set; }
        public string deviceCount { get; set; }
    }

    public class Attributes2
    {
        public string serial { get; set; }
        public string imei { get; set; }
        public string isLocked { get; set; }
        public string isLost { get; set; }
    }
}

Reading JSON:

string responseText = string.Empty;
AppleAPI appobj = new AppleAPI();
responseText = appobj.VerifyAppleESN(newEsn);
var resobj = JsonConvert.DeserializeObject<AppleAPI>(responseText.Replace("@",string.Empty));
lblSerialNumber.Text = resobj.product_info.serialNumber;
.
.
lblappliedActivationDetails.Text = resobj.ios_info.appliedActivationDetails;
.
.
//getting here error below line: Object ref notset to instance of object
lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;

Any Idea?


回答1:


If you're getting Object Reference not set to an instance of object. that means that you're trying to access properties on an object that is null. Since you said it happens on this line:

lblfmiVersion.Text = resobj.fmi.invalid_nameattribute.version;

that could mean that any of resobj, resobj.fmi, or resobj.fmi.invalid_nameattribute are null. Ignoring the fact that you should have proper null checks in your code to help avoid this situation, let's ask the question, why would any of these objects be null if deserialization succeeded? Perhaps some of the data was not deserialized correctly after all.

When deserializing using Json.Net, it is important to know that if any members of a class do not have matching properties in the JSON, those members will be skipped by Json.Net and thus retain their default values, e.g. null. So one possible reason that you have a null is that the name of a property in your class does not match what is in the JSON.

If we take a look at your Fmi class, one thing that jumps out right away is that it has a suspiciously named property called invalid_nameattribute. In the JSON, there is no such property. Instead, there is a property called @attributes. Your FmipLockStatusDevice class has the same problem. Since they didn't match up, these properties did not get populated during deserialization, so they are null.

So how can we fix this?

This is simple enough: add a [JsonProperty] attribute to your class properties to map them to the right JSON properties. (While you're at it, you might also consider changing the names of those properties in your C# class to something that actually makes sense, like "Attributes".)

public class Fmi
{
    [JsonProperty("@attributes")]
    public Attributes invalid_nameattribute { get; set; }
    public FmipLockStatusDevice fmipLockStatusDevice { get; set; }
}

public class FmipLockStatusDevice
{
    [JsonProperty("@attributes")]
    public Attributes2 invalid_nameattribute2 { get; set; }
}

OK, now that you have a solution, you should ask yourself, how did you get into this situation in the first place, and how can you avoid it in the future?

You said you used json2csharp.com to generate your classes. You need to be aware that this tool is not foolproof, and will not always be able to generate correct classes to work with your JSON. This is true whenever the JSON property names contain punctuation characters or spaces or start with numbers, because these cannot be turned into valid C# property names. In these cases, json2csharp.com will generate a property name that starts with "invalid". You need to look for these, and make manual adjustments to your classes to fix the issues. Do not just blindly use the generated classes and assume they are correct.

Hope this helps.



来源:https://stackoverflow.com/questions/24799363/object-reference-error-while-reading-specific-json-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!