E
E
Eugene Chefranov2020-05-09 18:51:09
C++ / C#
Eugene Chefranov, 2020-05-09 18:51:09

How to deserialize json and object value to insert into ComboBox?

Hello. I apologize in advance for the stupid question, I'm new to C#. I have a json file like this:

{
    "name": "SiO2",
    "h": 906,
    "s": -477,
    "a": 44,
    "b": 67,
    "c": 47
},
{
    "name": "Al2O3",
    "h": 805,
    "s": -155,
    "a": 53,
    "b": 73,
    "c": 62
},
...

I need to get the values ​​of the name field from each object and fill several ComboBoxes with them. After looking at the examples, as I understand it is necessary to create a class like this:
public class CompoundProps
    {
        public string name { set; get; }
        public float h { set; get; }
        public float s { set; get; }
        public float a { set; get; }
        public float b { set; get; }
        public float c { set; get; }
    }

And then deserialization like this:
using (FileStream fs = new FileStream("db1.json", FileMode.OpenOrCreate))
            {
                CompoundProps props = JsonSerializer.Deserialize<CompoundProps>(fs);
                Console.WriteLine($"Name: {props.name}  H: {props.h} S: {props.s} a: {props.a} b: {props.b} c: {props.c}");
            }

And with such an attempt, I get an error:
5eb6d074bfa57612287589.png
I didn’t reach the ComboBox filling, respectively ...
Tell me how to correctly get data from each object (using the name field as an example) and fill in several ComboBoxes (cb1, cb2, cb3)? If possible with comments on the code ♥

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Korotenko, 2020-05-09
@Chefranov

Your code is not valid

[{
    "name": "SiO2",
    "h": 906,
    "s": -477,
    "a": 44,
    "b": 67,
    "c": 47
  },
  {
    "name": "Al2O3",
    "h": 805,
    "s": -155,
    "a": 53,
    "b": 73,
    "c": 62
  }
]

using (FileStream fs = new FileStream("db1.json", FileMode.OpenOrCreate))
            {
                CompoundProps propss = JsonSerializer.Deserialize<CompoundProps[]>(fs.ReadToEnd());
                var props = propss[0];
                Console.WriteLine($"Name: {props.name}  H: {props.h} S: {props.s} a: {props.a} b: {props.b} c: {props.c}");
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question