Serializing the object containing the dictionary so that the keys / values โ€‹โ€‹of the dictionary are displayed as part of the containing object

I have a class as follows:

public class Usage
{
    public string app { get; set; }

    public Dictionary<string, string> KVPs { get; set; }
}

When I use this code:

var json = new JavaScriptSerializer().Serialize(usage);

he gives me this json:

{"app":"myapp", "KVPs":{"k1":"v1", "k2":"v2"}}

I would like it to return something like this:

{"app":"myapp", "k1":"v1", "k2":"v2"}

Is there any way to do this? I am currently using JavaScriptSerializer. If there is a way to do this using JSON.Net, I would like to switch to this.

+4
source share
2 answers

JSON.Net, Dictionary<string, string> Dictionary<string, object>, - [JsonExtensionData] , :

public class Usage
{
    public string app { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> KVPs { get; set; }
}

:

string json = JsonConvert.SerializeObject(usage);

JSON, :

{"app":"myapp","k1":"v1","k2":"v2"}

, JSON Usage , . JSON, , KVPs.

Usage usage = JsonConvert.DeserializeObject<Usage>(json);
+9

, ...

usage.KVPs["app"] = usage.app;
json = new JavaScriptSerializer().Serialize(usage.KVPs)
+2

Source: https://habr.com/ru/post/1529479/


All Articles