我如何通过c#访问json字符串中的任何键

本文关键字:字符串 任何键 json 访问 何通过 | 更新日期: 2023-09-27 18:02:41

我的问题很简单,但我不能那样做。我想通过c#代码从下面的字符串获得"soap:Body"的值?


{"soap:Envelope":{"xmlns:xsd":"http://www.w3.org/2001/XMLSchema","xmlns:soap":"http://www.w3.org/2003/05/soap-envelope","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","soap:Body":{"ToplamaResponse":{"xmlns":"http://tempuri.org/","ToplamaResult":156758}}}}

我如何通过c#访问json字符串中的任何键

如果你不想使用外部库,你也可以使用框架类JavaScriptSerializer。

string json = @"...";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var o = serializer.Deserialize<dynamic>(json);
var body = o["soap:Envelope"]["soap:Body"];

使用Json可以很容易地做到这一点。净

dynamic data = JObject.Parse("{'soap:Envelope':{'xmlns:xsd':'http://www.w3.org/2001/XMLSchema','xmlns:soap':'http://www.w3.org/2003/05/soap-envelope','xmlns:xsi':'http://www.w3.org/2001/XMLSchema-instance','soap:Body':{'ToplamaResponse':{'xmlns':'http://tempuri.org/','ToplamaResult':156758}}}}");
string soap_body = data["soap:Envelope"]["soap:Body"];

在JObject中有一个简单的例子。解析文档

string json = @"{
  "soap:Envelope": {
    "xmlns:xsd": "http://www.w3.org/2001/XMLSchema",
    "xmlns:soap": "http://www.w3.org/2003/05/soap-envelope",
    "xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
    "soap:Body": {
      "ToplamaResponse": {
        "xmlns": "http://tempuri.org/",
        "ToplamaResult": 156758
      }
    }
  }
}";
JObject obj = JObject.Parse(json);
Console.WriteLine((string)obj["soap:Envelope"]["soap:Body"]);

如果你想操作"soap:Body"的值,做同样的事情:)