Serialize .NET Dictionary into JSON Key Value Pair Object

后端 未结 1 1571
眼角桃花
眼角桃花 2020-12-01 10:16

I need to get:

public class Package
{
    public Package()
    {
        name = \"\";
        type = new List>();
             


        
相关标签:
1条回答
  • 2020-12-01 11:05

    Well, first off, for the first example, what you basically have is a list of collections of KeyValuePair<string,string> objects.

    So, the reason that it gets converted to the JSON shown is this:

    {
        "name":"package_name",
        "type":
        [ // List<Dictionary<string,string>>
            [ // Dictionary<string,string>, a list of KeyValuePair<string,string> objects
                { // KeyValuePair<string,string> object 
                    "Key":"http:\/\/random.url.as.key",
                    "Value":"random\/value"
                }
            ]
        ]
    }
    

    As far as your second example, you are creating a dynamic object, containing a dynamic object, and each of the object's fields are what are providing the key value.

    So, I would suggest ditching the outer List<> around the Dictionary<string,string>, then make use of the Newtonsoft.Json.Converters.KeyValuePairConverter object in the JSON.Net library when doing your serialization:

    string json = JsonConvert.SerializeObject( package, new KeyValuePairConverter( ) );
    

    Hope that helps.

    EDIT

    Okay, so I figured I should give a more concrete example

    public class Package
    {
        public Package()
        {
            name = "";
            type = new Dictionary<string, string>();
        }
    
        public string name { get; set; }
        public Dictionary<string, string> type { get; set; }
    }
    
    Package package = new Package();
    package.name = "package_name";
    package.type.Add("http://random.url.as.key", "random/value");
    string json = JsonConvert.SerializeObject( package, new KeyValuePairConverter( ) );
    

    This will get you the output

    {
        "name":"package_name",
        "type":
        {
            "http://random.url.as.key":"random/value"
        }
    }
    
    0 讨论(0)
提交回复
热议问题