2014-07-17 2 views
0

나는 JSON to C# Class Converter을 사용하고 다음과 같은 클래스 생성특정 JSON 문자열을 읽는 동안 객체 참조 오류가 발생 했습니까?

JSON 모든 데이터를 읽어 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":""}}} 

하지만 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"}}}, 

오류 :

개체 참조가 개체의 인스턴스로 설정되지 않았습니다.

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

읽기 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; 

어떤 생각?

답변

1

Object Reference not set to an instance of object.이 있으면 null 인 객체의 속성에 액세스하려고한다는 의미입니다. 당신이이 줄에서 발생했다 이후 :

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

중 하나가 resobj, resobj.fmi, 또는 resobj.fmi.invalid_nameattribute가 null 것을 의미 수 있었다. 이 상황을 피하기 위해 코드에서 적절한 null 검사를해야한다는 사실을 무시하고 질문을 해봅시다. 왜 직렬화가 성공하면이 객체 중 하나라도 null이 될까요? 아마도 일부 데이터는 결국 올바르게 직렬화되지 않았습니다.

Json.Net을 사용하여 비 직렬화 할 때 클래스의 멤버가 JSON에서 일치하는 속성을 갖고 있지 않으면 해당 멤버는 Json.Net에서 건너 뛴다는 사실을 알고 있어야합니다. null. 따라서 null을 가질 수있는 이유 중 하나는 클래스의 속성 이름이 JSON의 속성 이름과 일치하지 않는다는 것입니다.

Fmi 클래스를 살펴보면 곧바로 실행되는 것은 invalid_nameattribute이라는 의심스러운 속성이 있다는 것입니다. JSON에는 이러한 속성이 없습니다. 대신 @attributes이라는 속성이 있습니다. FmipLockStatusDevice 클래스에도 동일한 문제가 있습니다. 일치하지 않았기 때문에 이러한 속성은 deserialization 중에 채워지지 않으므로 null입니다.

어떻게 해결할 수 있습니까?

이것은 간단합니다. 클래스 속성에 [JsonProperty] 속성을 추가하여 올바른 JSON 속성에 매핑하십시오. (당신이 그것에 인 동안, 당신은 또한 실제로 "속성"과 같은 의미가 뭔가를 당신의 C# 클래스에서 해당 속성의 이름을 변경하는 것이 좋습니다.)

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

확인을, 지금은 해결책을 가지고 있음 , 당신은 스스로에게 물어봐야합니다. 어떻게 이런 상황에 처하게 되었습니까? 그리고 앞으로 어떻게 피할 수 있습니까?

json2csharp.com을 사용하여 수업을 생성했다고하셨습니다. 이 도구는 절대 안전한 것은 아니며 항상 JSON에 사용할 올바른 클래스를 생성 할 수있는 것은 아님을 알아야합니다.이것은 유효한 C# 속성 이름으로 바꿀 수 없기 때문에 JSON 속성 이름에 문장 부호 또는 공백이 있거나 숫자로 시작될 때마다 사실입니다. 이러한 경우 json2csharp.com은 "invalid"로 시작하는 속성 이름을 생성합니다. 이러한 문제를 해결하려면 클래스를 수동으로 조정해야합니다. 생성 된 클래스를 맹목적으로 사용하지 않고 올바른 클래스라고 가정합니다.

희망이 도움이됩니다.

+0

안녕하세요 @Brian Rogers! 너 정말 대단해! 당신은 오류 소스를 알려주는 유일한 사람입니다! 그리고 이러한 훌륭한 Explaination을 솔루션과 함께 자세히 설명합니다! 단순히 대단합니다! 나를 가리켜 주셔서 고맙다 "사용하지 않는 utitlity"와 나는 동의한다! 그것은 처음 시도에서 일했습니다! 감사합니다 +1 : –

+0

@SHEKHARSHETE 문제 없습니다. 내가 도울 수있어서 기뻐. –