1

I have 2 C# class:

public class Light
{
    public int Brightness { get; set; }
    public string Mode { get; set; }
}

public class AirConditioner
{
    public int Temperature{ get; set; }
    public string Mode { get; set; }
}

JSON file format:

{
  "Light": {
    "Brightness": 5,
    "Mode": "On"
  },
  "AirConditioner": {
    "Temperature": 25,
    "Mode": "Cooling"
  }
}

I want to parse JSON file to C# by section, something like this:

var light = JsonDeserialize<Light>.(FileSection["Light"]);
var aircon = JsonDeserialize<AirConditioner>.(FileSection["AirConditioner"]);

What I want is the same as Asp.Net Core configuration work:

var light = new Light();
Configuration.GetSection("Light").Bind(light);

It will be better if I do not need to install other packages.

Thank you for your help.

Update: The problem is how to get a section of the JSON file. If I can get the Light section like this:

var lightString = JsonFile.GetSection("Light");

Then I can simply deserialize with System.Text.Json namespace:

var light = JsonSerializer.Deserialize<Light>(lightString);
Nam Pham
  • 23
  • 1
  • 6
  • You may try Newtonsoft: using Newtonsoft.Json; var json = JsonConvert.DeserializeObject(FileSection["Light"]); – fatihyildizhan Apr 28 '21 at 04:56
  • You may also read JSON file from the folder like this: https://stackoverflow.com/questions/67102873/c-sharp-net5-single-file-application-read-and-parse-json-txt-or-other-file-fo/67102874#67102874 – fatihyildizhan Apr 28 '21 at 04:57
  • Cannot deserialize without definding new class. The problem is how to get the "Light" section to string. – Nam Pham Apr 28 '21 at 05:17
  • https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm – Self Apr 28 '21 at 06:46

2 Answers2

0

I have done this by creating a parent class that holds the Light and AirConditioner properties.

The parent Class:

public class Devices
{
    public Light Light {get;set;}
    public AirConditioner AirConditioner {get;set;}
}

Then you can de-serialize into the Devices and access the light and airconditioner.

var devices = JsonDeserialize<Devices>.(myjsonfilecontent);
var light = devices.Light;
var aircon = devices.AirConditioner;

  • I thought about your method but it is needed to define new class. – Nam Pham Apr 28 '21 at 05:15
  • @NamPham, New class is a simple copy past. in visual studio you have special past that does that for you. It's a no cost. there is a ton a free online tool that will do that too : https://app.quicktype.io, with a simple past of your json – Self Apr 28 '21 at 06:48
  • Any implementation will require parsing the entire JSON string. Selecting the property will not stop that from happening. If you do want that behavior @moreON mentioned in the other answer a good source that has some helper methods to do what you want. – Jordon Kraft Apr 29 '21 at 22:12
0

I think you're looking for https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm in Newtonsoft's JSON.Net

It allows for manipulating of a whole JSON object as very generic JOBject and locating and converting only the parts you need.

In your example this looks something like the following. This code uses the newtonsoft.json package.

using System;
using Newtonsoft.Json.Linq;

namespace SO_67293726
{

    public class Light
    {
        public int Brightness { get; set; }
        public string Mode { get; set; }
    }

    public class AirConditioner
    {
        public int Temperature { get; set; }
        public string Mode { get; set; }
    }

    class Program
    {
        public static string JsonString =>
@"{
  ""Light"": {
    ""Brightness"": 5,
    ""Mode"": ""On""
  },
  ""AirConditioner"": {
    ""Temperature"": 25,
    ""Mode"": ""Cooling""
  }
}";
        static void Main(string[] args)
        {
            var jobject = JObject.Parse(JsonString);
            var light = jobject["Light"].ToObject<Light>();
            var aircon = jobject["AirConditioner"].ToObject<AirConditioner>();
        }
    }
}
moreON
  • 1,977
  • 17
  • 19
  • Note that doing this simply as part of `System.Text.Json` is still an open issue https://github.com/dotnet/runtime/issues/31274 . An existing question https://stackoverflow.com/questions/58138793/system-text-json-jsonelement-toobject-workaround may help if you're committed to avoiding newtonsoft.json – moreON Apr 28 '21 at 05:55
  • Thank you for your reply. This is really what I am looking for. Although I need to install Newtonsoft.Json package. Waiting for dotnet support this feature. – Nam Pham Apr 30 '21 at 01:25