将JSON反序列化为C#变量

时间:2016-12-23 07:27:36

标签: c# json

嗨我想在c#中将这个json字符串读入我的局部变量,任何人都可以告诉我该怎么做

{  
   "type":"object",
   "error":"",
   "warning":"",
   "info":"",
   "response_code":"200",
   "response":[  
      {  
         "MeterID":"6",
         "KWHMainActual":"0.0",
         "KWActual":"0 ",
         "KWHDGActual":"0.2",
         "MeterOnOff":"1",
         "MeterDefective":"0",
         "RecordDateTime":"2016-08-17 12:46:49.000"
      }
   ]
}

1 个答案:

答案 0 :(得分:1)

要生成类,您可以使用JSON2CSHARP并对您的JSON使用Json.NET进行反序列化。

型号:

 public class Response
    {
        public string MeterID { get; set; }
        public string KWHMainActual { get; set; }
        public string KWActual { get; set; }
        public string KWHDGActual { get; set; }
        public string MeterOnOff { get; set; }
        public string MeterDefective { get; set; }
        public string RecordDateTime { get; set; }
    }

    public class RootObject
    {
        public string type { get; set; }
        public string error { get; set; }
        public string warning { get; set; }
        public string info { get; set; }
        public string response_code { get; set; }
        public List<Response> response { get; set; }
    }

和反序列化方法

JsonConvert.DeserializeObject<RootObject>("jsonString");

修改:

使用WebRequest您可以从uri获取json,尝试使用此方法

public async Task<string> GetFromUri(string uri)
    {
        var request = (HttpWebRequest) WebRequest.Create(new Uri(uri));
        request.ContentType = "application/json";
        request.Method = "GET";

        // Send the request to the server and wait for the response:  
        using (var response = await request.GetResponseAsync())
        {
            // Get a stream representation of the HTTP web response:  
            using (var stream = response.GetResponseStream())
            {
                var reader = new StreamReader(stream);
                var message = JsonConvert.DeserializeObject<string>(reader.ReadToEnd());
                return message;
            }
        }
    }

通话方法

 var jsonString = await GetFromUri("uri");