Skefrep
Skefrep

Reputation: 53

Json serialization of a nested Dictionary returns { "key": "key1", "value": "value1" }

I'm currently working on a webservice, and I have this behavior that I haven't encountered until today. Here's the class I'm returning:

public class Block
{
    public int order { get; set; }
    public string title { get; set; }
    public Dictionary<string, object> attributes { get; set; }
}

attributes can contain any kind of value: simple type, object, array, etc.

And when I return a Block object through my webservice, here's what I get:

{
    "order": 1,
    "attributes": [
        {
            "Key": "key1",
            "Value": "value1"
        },
        {
            "Key": "key2",
            "Value": "value2"
        }
    ],
    "title": "Title"
}

Does anyone know why I'm not simply getting a "key1": "value1" output?

Upvotes: 0

Views: 197

Answers (2)

Hans Kilian
Hans Kilian

Reputation: 25100

When I do

    var x = new Class
    {
        order = 1,
        title = "Title",
        attributes = new Dictionary<string, object>
        {
            { "key1", "value1" },
            { "key2", "value2" }
        }
    };

    var json = JsonConvert.SerializeObject(x);
    Console.WriteLine(json);

I get

{"order":1,"title":"Title","attributes":{"key1":"value1","key2":"value2"}}

Do you have code that serializes your data or does ASP.NET do it for you?

Upvotes: 1

Shino Lex
Shino Lex

Reputation: 525

First of all your JSON is not valid, please be aware there are no , after "order": 1 this line.

After this correction you can change your class structure like this

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

    public class Block
    {
        public int order { get; set; }
        public List<Attribute> attributes { get; set; }
        public string title { get; set; }
    }

this way you will be able to deserialize your JSON, I used simply this website https://json2csharp.com/ for converting your JSON into C# class

As for usage you can do .FirstOrDefault(x=>x.Key=="key1") to get whichever data you want, or if you will process all the list one by one you can simply do attributes.Count

Upvotes: 1

Related Questions