简体   繁体   中英

Deserialize Json into C#

I got some Json, that looks like this:

[
  {
    "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.

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....

You can use Json.Linq to get a list of Sample objects from your json. Parse json to JArray instance, then enumerate all properties of the last object to get the names and values

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

Per your posted JSON, you would get a model like below. Use 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.

An easy way is to Copy JSON to clipboard -> Open Visual Studio -> Edit -> Paste Special -> Paste JSON as classes .

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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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