如何在c#中读取动态返回的JSON字符串

本文关键字:返回 JSON 字符串 动态 读取 | 更新日期: 2023-09-27 18:13:16

我有一个Apple API,它使用SerialNumber/IMEI数字返回Apple设备信息并返回JSON字符串。

并且已经成功地使用JSON创建了一个类到c#类转换器,它工作得很好。但是,问题是,当我调用Out of Warranty[已通过保修的设备返回不同的JSON]设备时,它返回具有不同键值的JSON,因此RootObject的铸造失败。

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

}

源代码:

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

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

所以,我想知道我们是否可以读取动态返回的JSON字符串并在html表中显示,而不知道它的键和项数。

注意:我使用。. NET Framework 3.5所以不能使用dynamic关键字,因为许多示例使用 4.0版本

更新:

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

在尝试了@tt_emrah的建议代码并进行了一定程度的修改后,我得到了以下字符串:

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

但是如何获得键:值格式的值

注意:返回的JSON字符串可能会改变。所以独立于返回的JSON字符串只是想显示它为键:值

例子:

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

帮助感激!

如何在c#中读取动态返回的JSON字符串

为什么不将字符串反序列化为字典,然后遍历显示部分的键呢?

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