Home > Software engineering >  how convert key value class to json
how convert key value class to json

Time:03-02

i am a class with definition below

 public class Param
    {
        public string Key { get; set; }
        public object Value { get; set; }

        public Param(string key, object value)
        {
            this.Key = key;
            this.Value = value;
        }
    }

a objects with values

var params = new List<Param>(){new Param("k1","v1"),new Param("k2","v2"),new Param("k3","v3")};

How to build a json with this structure.

{
"k1":"v1",
"k2":"v2",
"k3":"v3"
}

CodePudding user response:

var json = JsonSerializer.Serialize(params.ToDictionary(p => p.Key, p => p.Value));
  • Related