3

I would like to serialize a Dictionary to a JSON array with ASP.NET Web API. To illustrate the current output I have the following setup:

Dictionary<int, TestClass> dict = new Dictionary<int, TestClass>();
dict.Add(3, new TestClass(3, "test3"));
dict.Add(4, new TestClass(4, "test4"));

The TestClass is defined as follows:

public class TestClass
{
    public int Id { get; set; }
    public string Name { get; set; }

    public TestClass(int id, string name)
    {
        this.Id = id;
        this.Name = name;
    }
}

When serialized to JSON I get the following output:

{"3":{"id":3,"name":"test3"},"4":{"id":3,"name":"test4"}} 

Unfortunately this is an Object and not an Array. Is it somehow possible to achieve what I'm trying to do? It doesn't need to be a Dictionary but I need the Id's of the TestClass to be the Key's of the Array.

With the following List it is correctly serialized to an array but not with the correct Key's.

List<TestClass> list= new List<TestClass>();
list.Add(new TestClass(3, "test3"));
list.Add(new TestClass(4, "test4"));

Serialized to JSON:

[{"id":3,"name":"test3"},{"id":4,"name":"test4"}] 

2 Answers 2

3

but I need the Id's of the TestClass to be the Key's of the Array.

In javascript what you call an array must be an object in which the indexes are 0-based integers. This is not your case. You have id 3 and 4 which cannot be used as indexes in a javascript array. So using a List is the correct approach here.

Because if you want to use arbitrary indexes (as in your case you have some integers that are not 0-based) this is no longer an array but an object in which those integers or strings are simply the properties of this object. That's what you achieve with the Dictionary.

Sign up to request clarification or add additional context in comments.

Comments

0

You could convert the object to an array client-side using vanilla js.

var jsonFromServer = {"3":{"id":3,"name":"test3"},"4":{"id":4,"name":"test4"}};
var expected = [];
Object.keys(jsonFromServer).forEach(key => expected[+key] = json[key]);

console.log(expected.length); // 5
console.log(expected[0]);     // undefined
console.log(expected[1]);     // undefined
console.log(expected[2]);     // undefined
console.log(expected[3]);     // Object { id: 3, name: "test3" }
console.log(expected[4]);     // Object { id: 4, name: "test4" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.