0

I have the "json" mentioned below. "changes" property is changeable

{"sort":[{"field":"recid","direction":"desc"}],"changes":[{"recid":2084,"LokasyonAdresi":"211","LokasyonAdi":"111"}],"action":"save"}

When I convert json to c# classes, the following classes are created.

public class Sort
    {
        public string field { get; set; }
        public string direction { get; set; }
    }

    public class Change
    {
        public int recid { get; set; }
        public string LokasyonAdresi { get; set; }
        public string LokasyonAdi { get; set; }
    }

    public class Root
    {
        public List<Sort> sort { get; set; }
        public List<Change> changes { get; set; }
        public string action { get; set; }
    }

I want the class I want to convert to be like this. How can I customize?

public class Root
{
    [JsonPropertyName("sort")]
    public IList<Sort> Sort { get; set; }

    [JsonPropertyName("action")]
    public string Action { get; set; }

    [JsonPropertyName("changes")]
    public IDictionary<string, object> Changes { get; set; }
}
Serge
  • 40,935
  • 4
  • 18
  • 45
  • 1
    In your JSON sample, `"changes"` is an **arrray** not an **object**. If you want to deserialize an array as an object, you need to explain what you want to do for the property names of the array items when you convert each `object` item to a `KeyValuePair` dictionary entry. – dbc Jan 01 '22 at 22:37

1 Answers1

0

try this code

var jsonParsed = JObject.Parse(json);

Dictionary<string,object> changes=((JArray)jsonParsed["changes"])
.SelectMany(x=> x.ToObject<Dictionary<string,object>>())
.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value); 

List<Sort> sort= ((JArray) jsonParsed["sort"]).Select(x=> x.ToObject<Sort>()).ToList();

    var data = new Root { 
      Action= (string) jsonParsed["action"], 
      Sort= sort,
      Changes=changes
      };
Serge
  • 40,935
  • 4
  • 18
  • 45
  • thanks for your answer. but i am not using newtonsoft json. How can I do this with system.text.json. – Mansur Değirmenci Jan 02 '22 at 09:53
  • @MansurDeğirmenci system.text.json. has more bugs then the line of codes , I am not sure if it is possible to do something using it – Serge Jan 02 '22 at 10:26