简体   繁体   中英

C#: Returning Javascript Object Collection vs Array of Objects

I'm using a 3rd party map for some charting functionality within our intranet. To populate the regions, I need to pass it an Object Collection (javascript) formatted thusly:

            simplemaps_usmap_mapdata.state_specific = {
            AZ: {
                name: "Arizona",
                description: "The best state in the whole got damn union",
                color: "#cecece",
                hover_color: "default",
                url: "",
              },
            NH: {
                name: "New Hampshire",
                description: "Small and insignificant",
                color: "#f68831",
                hover_color: "default",
                url: "",
              }
        }

Obviously, it'd be much better if it were an array of objects, then it'd be simple enough to return via my C# controller a List, but since it's an object collection, what is the best way to return JSON formatted this way via my C# controller?

First, a class:

class MyClass {
    public string name {get;set;}
    public string description {get;set;}
    public string color {get;set;}
    public string hover_color {get;set;}
    public string url {get;set;}
}

Then, a dictionary:

var result = new Dictionary<string, MyClass>();

Add to the dictionary:

result["AZ"] = new MyClass { name="xyz"... };

Finally, return the dictionary via the JSON method:

return JSON(result);

I am going to assume you have already configured your controller to return JSON, meaning your object type is the only thing that needs to be setup.

The problem with this format, as you are likely already aware of, is that you will need to define an object that has all of the states on it's root level. This is tedious and likely overkill when you don't need every single state to be returned.

To solve this, utilize either the dynamic type or an anonymous object in C#. This will allow you to define just what you need at that time:

Pseudocode for your controller method:

public dynamic MyAction() // Dynamic
public object MyAction() // Object
{
    return new {
        AZ = new StateObj(), // Insert your state type here
        NH = new StateObj()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM