简体   繁体   English

将 Json 反序列化为 C#

[英]Deserialize Json into C#

I got some Json, that looks like this:我得到了一些 Json,看起来像这样:

[
  {
    "starttime": "2020-02-27T14:30:00Z",
    "endtime": "2020-02-27T14:40:00Z"
  },
  {
    "Temp": {
      "value": 3
    },
    "Pressure": {
      "value": 29
    },
    "Humidity": {
      "value": 85
    }
  }
]

I would like to deserialize it onto a object on the form:我想将它反序列化到表单上的一个对象上:

public class Sample {
   public string Name {get; set;}
   public int Value {get;set;}
}

and then get 3 instances where name is set to either Temp, Pressure, Humidity, and Value set to 3, 29, 85 I don't really care about the start-/endtime part.然后得到 3 个实例,其中名称设置为温度、压力、湿度和值设置为 3、29、85 我并不真正关心开始/结束时间部分。

Any help would be greatly appreciated...任何帮助将不胜感激...

/Søren /索伦

Update:更新:

Came up with this myself:我自己想出了这个:

var tmp = JsonConvert.DeserializeObject<JArray>(content);

var samples = tmp.
    SelectMany(x => ((JToken) x).Children())
    .Where(x => !((JProperty) x).Name.Contains("time"))
    .Select(x =>
    {
        var tmp2 = x.First.ToObject<Sample>();
        tmp2.name = ((JProperty) x).Name;
        return tmp2;
    })
    .ToList();

but I think Pavel's solution below, is more readable....但我认为下面 Pavel 的解决方案更具可读性....

You can use Json.Linq to get a list of Sample objects from your json.您可以使用Json.Linq从您的 json 中获取Sample对象的列表。 Parse json to JArray instance, then enumerate all properties of the last object to get the names and values将json解析为JArray实例,然后枚举最后一个对象的所有属性以获取名称和值

var array = JArray.Parse(json);

var samples = ReadSamples(array.Last());
foreach (var sample in samples)
{
    Console.WriteLine($"{sample.Name} {sample.Value}");
}

IEnumerable<Sample> ReadSamples(JToken data)
{
    foreach (JProperty item in data)
    {
        yield return new Sample()
        {
            Name = item.Name,
            Value = item.Value["value"]?.Value<int>() ?? 0
        };
    }
}

The output will be the following输出将如下

Temp 3
Pressure 29
Humidity 85

It's also possible to do the same using System.Text.Json API, which is available from .NET Core 3.x也可以使用System.Text.Json API 执行相同的操作,该 API 可从 .NET Core 3.x 获得

Per your posted JSON, you would get a model like below.根据您发布的 JSON,您将获得如下所示的模型。 Use http://json2csharp.com/#使用http://json2csharp.com/#

public class Temp
{
    public int value { get; set; }
}

public class Pressure
{
    public int value { get; set; }
}

public class Humidity
{
    public int value { get; set; }
}

public class RootObject
{
    public DateTime starttime { get; set; }
    public DateTime endtime { get; set; }
    public Temp Temp { get; set; }
    public Pressure Pressure { get; set; }
    public Humidity Humidity { get; set; }
}

If your JSON is not dynamic, creating classes which model your JSON is a good idea.如果您的 JSON 不是动态的,那么创建为您的 JSON 建模的类是个好主意。

An easy way is to Copy JSON to clipboard -> Open Visual Studio -> Edit -> Paste Special -> Paste JSON as classes .一种简单的方法是将 JSON 复制到剪贴板 -> 打开 Visual Studio -> 编辑 -> 选择性粘贴 -> 将 JSON 粘贴为类

This should give you the following classes:这应该为您提供以下课程:

public class Class1
{
    public DateTime starttime { get; set; }
    public DateTime endtime { get; set; }
    public Temp Temp { get; set; }
    public Pressure Pressure { get; set; }
    public Humidity Humidity { get; set; }
}

public class Temp
{
    public int value { get; set; }
}

public class Pressure
{
    public int value { get; set; }
}

public class Humidity
{
    public int value { get; set; }
}

And now you can deserialize the JSON array to List<Class1> using the Newtonsoft.Json NuGet package:现在您可以使用Newtonsoft.Json NuGet 包将 JSON 数组反序列化为List<Class1>

using Newtonsoft.Json;
using System.Collections.Generic;

...

string json = @"[
  {
    ""starttime"": ""2020 - 02 - 27T14: 30:00Z"",
    ""endtime"": ""2020-02-27T14:40:00Z""
  },
  {
    ""Temp"": {
      ""value"": 3
    },
    ""Pressure"": {
      ""value"": 29
    },
    ""Humidity"": {
      ""value"": 85
    }
  }
]";

var myObject = JsonConvert.DeserializeObject<List<Class1>>(json);

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

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