【问题标题】:How to read dynamic returned JSON string in c#?如何在 C# 中读取动态返回的 JSON 字符串?
【发布时间】:2014-07-16 13:19:16
【问题描述】:

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

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

JSON 1:[用于保修设备]

{
"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:[用于超出保修期的设备]

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

所以,我想知道 我们是否可以在不知道其键和项数的情况下读取 Dynamic 返回的 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": "" } } 

但是如何获取 Key:Value 格式的值。

注意: 返回的JSON 字符串可能会改变。所以独立于返回的JSON 字符串只想将其显示为 Key:Values

示例:

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

帮助赞赏!

【问题讨论】:

  • 您可能需要在反序列化之前检查字符串以确定它是否在保修期内或不在保修范围内,然后反序列化到不同的类以确保保修外。
  • 嗨@MattBurland!是的!我已经为超出保修期创建了不同的类并且它可以工作。但是,如果我得到除这两个以外的其他 JSON 字符串怎么办?作为它的“未确定”和“未知”。所以,我需要一些可以读取任何 JSON 字符串并显示在 HTML 表中的东西。有什么想法吗?
  • 没有动态类型,这非常困难。您也许可以将字符串转换为字典?这个问题可能会有所帮助:stackoverflow.com/questions/14886800/…
  • 嗨@MattBurland!请检查更新你能帮我吗?

标签: c# json json-deserialization


【解决方案1】:

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

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

【讨论】:

  • 嗨@tt_emrah,请查看主帖中的“更新”!帮助欣赏!
  • 您可以在递归方法中执行此操作,并检查每个值是否也是 JObject 的实例。我修改了上面的代码。
  • 谢谢它的工作,我会做出相应的改变!你能帮我吗:stackoverflow.com/questions/24799363/…
  • 以上问题我已经解决了!只是最后一个问题,我可以得到特定的密钥:即我想读取“fmi”(请参考 JSON1 字符串)& 它的内部内容只会你 plz 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
相关资源
最近更新 更多