简体   繁体   English

c#反序列化Json字符串

[英]c# Deserialize Json String

I'm new to REST (moving from SOAP).我是 REST 的新手(从 SOAP 开始)。 I'm trying to deserialize a JSON string i'm getting as result to a REST API call.我正在尝试反序列化作为 REST API 调用的结果的 JSON 字符串。

This is the json string:这是 json 字符串:

{
  "message": "SUCCESS",
  "result": "{\"code\":\"610a187f80e24542bd5342d93c810a04\",\"rtime\":\"2021-06-17 19:40:03\",\"data\":\"08000002=2021-06-17 19:42:06\",\"ref_code\":\"\",\"stime\":\"2021-06-17 19:40:03\",\"source\":\"inhe-iot-crw_192_168_0_201_7021\",\"cycle\":0,\"operator\":\"ADMIN\",\"head\":\"inhe-ami-center/51ad33de59bb44dda693ec9811cec826\",\"result\":\"S\",\"times\":0,\"dev\":{\"ptct\":\"1/1|1/1\",\"svn_type\":\"791f88ae4392a682eb74\",\"con\":\"\",\"scheme\":\"DLMS_WRAPPER_645\",\"svn_no\":12,\"id\":\"00036178fedf95aa8b68\",\"addr\":\"037222663645\"},\"op_content\":\"037222663645||0\",\"ptime\":\"2021-06-17 19:40:03\",\"op_times\":\"0\",\"module_type\":\"001\",\"ip\":\"\",\"params\":\"\",\"priority\":9,\"packet\":\"S:0001000100010018E6000508AAA4C5DD68453666227203681104D3343337CE16,R:FEFEFEFE6845366622720368910BD334333733395D464439482916\",\"cmd_type\":\"R-READ\",\"field\":\"08000002\",\"expire\":10,\"etime\":\"2021-06-17 19:40:04\",\"data_ptct\":\"08000002=2021-06-17 19:42:06\"}",
  "code": 0,
  "sign": "d488e1e531837929faeac2518c1659e6",
  "timestamp": 1623969605496
}

What i need in the value for rtime field.我在 rtime 字段的值中需要什么。

This is my code:这是我的代码:

var json_serializer = new JavaScriptSerializer();
        var routes_list = (IDictionary<string, object>)json_serializer.DeserializeObject(AMI_GetResult.GetResult(data));    
        return string.Concat(routes_list["rtime"]);

I'm receiving this error:我收到此错误:

System.Collections.Generic.KeyNotFoundException System.Collections.Generic.KeyNotFoundException

I understand that rtime is not being found in the parse, my question is:我知道在解析中没有找到 rtime,我的问题是:

How can i get the timestamp value for rtime?如何获取 rtime 的时间戳值?

Thanks for your help.谢谢你的帮助。

Result property does not contain another json object it contains json string, you need to deserialize it again. Result 属性不包含另一个 json 对象它包含 json 字符串,您需要再次反序列化它。 For example using Json.NET it can look something like that:例如使用 Json.NET,它看起来像这样:

public class Outer
{
    public string Result { get; set; }
}

public class Inner
{
    public string RTime { get; set; } // or even make it of type DateTime, but there can be some format related issues
}

var outer = JsonConvert.DeserializeObject<Outer>(json);
var inner = JsonConvert.DeserializeObject<Inner>(outer.Result); // RTime prop will contain needed data 

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

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