简体   繁体   中英

How do I get a JavaScript array of an array of strings into a C# data structure?

I've been trying for the past hour and can't get it. At this point my controller looks like

public ActionResult GenerateMasterLink (string assetsJSON)
{
   ...
}

and I've confirmed that it is being passed a string like

[["Microsoft","Azure","roman_column.png"],["Microsoft","Azure","runphp.cmd"],["Microsoft","Azure","runphp.cmd"],["Microsoft","Azure","Picture1.png"],["Microsoft","Azure","vertical-align-scrnsht.png"],["Microsoft","Azure","vertical-align-scrnsht.png"]]

The only question I have is how I get the damned stuff out of it!

I've tried creating a class

    public class ThreePartKey
    {
        public string organizationName { get; set; }
        public string categoryName { get; set; }
        public string fileName { get; set; }
    }

and then done

ThreePartKey [] assetList = new JavaScriptSerializer().Deserialize<ThreePartKey []>(assetsJSON);

which gives me

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

in my browser's console some of the time, and other times gives me

Additional information: Type 'AllyPortal.Controllers.SurfaceAssetsController+ThreePartKey' is not supported for deserialization of an array.

as a Visual Studio error.

I've experimented with a million things and can't get this right. All I want is to have the JSON in some C# data structure where I can actually use it in my controller. Any suggestions?

You are trying to deserialize to incompatible model. You string input can be deserialized into string[][] variable but in order to allow deserializations into an ThreePartKey you need to name those values per property: [[organizationName: "Microsoft",...]] This will copy right value to your model

The problem is that your target datatype doesn't match the source datatype.

If you are converting an array of array of strings, you must deserialize into another array of array of strings, only them, you'll be able to convert it into whatever you want:

In short, replace

ThreePartKey [] assetList = new JavaScriptSerializer().Deserialize<ThreePartKey []>(assetsJSON);

for

ThreePartKey[] assetList = new JavaScriptSerializer().Deserialize<string[][]>(assetsJSON)
                .Select(el => new ThreePartKey() {organizationName = el[0], categoryName = el[1], fileName = el[2]})
                .ToArray();

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