简体   繁体   English

如何获取json字符串某些部分的值?

[英]How can I get the values of some part of a json string?

I'm working with this Json structure, but I don't know how to get the values of the part of the "json" key 我正在使用此Json结构,但我不知道如何获取“ json”键的一部分的值

I'm using this code to send a request to an API, and the return is an Json object: 我正在使用此代码向API发送请求,返回的是Json对象:

var reqData = (HttpWebRequest)WebRequest.Create(string.Format("http://server_ip/system/message/date/{0}/", txtDate.Text));
            reqData.ContentType = "application/json";
            reqData.Method = "GET";


var answer = (HttpWebResponse)reqData.GetResponse();
List<Dictionary<string, string>> convert = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(answer);

The result is a Json structure like this: 结果是这样的Json结构:

"[
  {
   \"idMessage\":\"--Message Id--",
   \"idTemplate\":--TemplateId--,
   \"mail\":\"--mail dir--\",
   \"subject\":\"--message subject--\",
    \"json\":\"{
                \\\"Id\\\":\\\"--Person Id--\\\",
                \\\"name\\\":\\\"--Person name--\\\",
                \\\"date\\":\\\"--Register date-\\\",
                \\\"hour\\\":\\\"--Register hour--\\\"
               }\",
    \"senddate\":\"--sent date--\",
    \"status\":0,
    \"template\":null
   }
  ]"

I want to get the values ( Id,name,date,hour ) from the json part of this Json string, can someone help me to get this values? 我想从此Json字符串的json部分获取值( Id,name,date,hour ),有人可以帮助我获取此值吗?

That json property contains a string of more JSON, so you have to deserialize that again, the same way you did the whole outer structure. json属性包含一个包含更多JSON的字符串,因此您必须再次对它进行反序列化,就像处理整个外部结构一样。

So now that you have your convert array, you can pull out the first object, grab the value of json and deserialize that: 因此,现在有了您的convert数组,您可以拉出第一个对象,获取json的值并将其反序列化:

var json = JsonConvert.DeserializeObject<Dictionary<string, string>>(convert[0]["json"]);

Then you can pull each value out like this: 然后,您可以像这样提取每个值:

var id = json["Id"];

Mind you, the JSON in your question isn't actually valid. 请注意,您问题中的JSON实际上无效。 There are a few errors in it. 其中有一些错误。 But I'm assuming that they're just copy/paste errors and the web service is actually returning valid JSON. 但是我假设它们只是复制/粘贴错误,并且Web服务实际上正在返回有效的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM