SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6066

How to read dynamic returned JSON string in c#?

I have a an Apple API which returns the Apple Device information using the SerialNumber/IMEI number and returns the JSON string.

And have successfully have created a Classes using JSON to C# Class Converter and it works fine. But, the problem is, when i make a call for Out of Warranty[the device which has passed warranty it returns different JSON] device it returns JSON with different Key,Values hence the casting of RootObject fails.

JSON 1: [For in Warranty Device]

{
"ios_info": {
    "serialNumber": "F2LLMBNJF",
    "imeiNumber": "013884004132",
    "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": "F2LLMBNJF",
            "imei": "013884004132",
            "isLocked": "true",
            "isLost": "false"
        }
    }
},
"product_info": {
    "serialNumber": "F2LLMBNJF",
    "warrantyStatus": "Apple Limited Warranty",
    "coverageEndDate": "11/25/14",
    "coverageStartDate": "11/26/13",
    "daysRemaining": "498",
    "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": ""
    }
}

}

JSON 2: [For Out of Warranty Device]

{
"ios_info": "Provided serial number does not belong to an iOS Device.Please Enter an ios serial number.",
"product_info": {
    "serialNumber": "C02HW2LGD",
    "warrantyStatus": "Out Of Warranty (No Coverage)",
    "daysRemaining": "0",
    "estimatedPurchaseDate": "07/20/12",
    "purchaseCountry": "United States",
    "registrationDate": "",
    "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": "MacBook Pro (Retina, Mid 2012)",
    "configDescription": "MBP 15.4/2.3/8GB/256GB FLASH",
    "slaGroupDescription": "",
    "acPlusFlag": "",
    "consumerLawInfo": {
        "serviceType": "",
        "popMandatory": "",
        "allowedPartType": ""
    }
}

}

Source Code:

public class AppleAPI
{
    public IosInfo ios_info { get; set; }
    public ProductInfo product_info { get; set; }

    public bool error { get; set; }
    public string error_message { get; set; }
    public AppleAPI()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public string VerifyAppleESN(string esn)
    {
        string responseText = string.Empty;
    //Apple API code here
        return responseText;
    }
}
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; }
}

Deserialisation of JSON:

string responseText = string.Empty;
AppleAPI appobj = new AppleAPI();
responseText = appobj.VerifyAppleESN(newEsn);
//Below line works only wen Device is in Warranty & if Out of Warranty it gives error.
var resobj = JsonConvert.DeserializeObject<AppleAPI>(responseText);

So, i want to know whether we can read the Dynamic returned JSON string and display in html table without knowing its key and number of items.

NOTE: I am using .NET Framework 3.5 so can't use dynamic key word as many samples are available using version 4.0

Update:

var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseText);
  string sdict = string.Empty;
  string innertval = string.Empty;
  foreach (string key in resDict.Keys)
  {
      sdict += "<br/> " +key+" "+ resDict[key].ToString();
  }

After trying the suggested code from @tt_emrah and modifying at certain extent i got the following STRING :

ios_info Provided serial number does not belong to an iOS Device.Please Enter an ios serial number.
product_info { "serialNumber": "C02HW2LGDKQ", "warrantyStatus": "Out Of Warranty (No Coverage)", "daysRemaining": "0", "estimatedPurchaseDate": "07/20/12", "purchaseCountry": "United States", "registrationDate": "", "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": "MacBook Pro (Retina, Mid 2012)", "configDescription": "MBP 15.4/2.3/8GB/256GB FLASH", "slaGroupDescription": "", "acPlusFlag": "", "consumerLawInfo": { "serviceType": "", "popMandatory": "", "allowedPartType": "" } } 

But how to get the values as Key:Value format.

NOTE: The returned JSON string may change. so Independent of returned JSON string just want to display it as Key:Values

Example:

     serialNumber:C02HW2LGDKQ
     warrantyStatus:Out of Warranty(No Coverage)
     .
     (n) key:values

Help Appreciated!

Upvotes: 0

Views: 488

Answers (1)

tt_emrah
tt_emrah

Reputation: 1053

why not deserialize the string into a dictionary, and then iterate through it's keys for the display part?

    private string GetKeyValuePairs(string jsonString)
    {
        var resDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonString);
        string sdict = string.Empty;
        foreach (string key in resDict.Keys)
        {
            sdict += "<br/> " + key + " : " + (resDict[key].GetType() == typeof(JObject) ? GetKeyValuePairs(resDict[key].ToString()) : resDict[key].ToString());
        }
        return sdict;
    }

Upvotes: 2

Related Questions