2

Is there a way to deserialize an array sent by jquery post method to directly c# string array(string[])?

I tried posting data like this

$.post(url,
          {
           'selectedTeams[]'=['Team1','Team2']
          },
          function(response) {}, 'json');

And trying to consume it like this in C# class

string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
var selectedTeams = new JavaScriptSerializer().Deserialize<string[]>(jsonData);

It didn't work and ofcource it should not as there is no property selectedTeams[] in string[]

I am aware of the way to define a class something like this

class Teams
{
   public string[] SelectedTeams{get;set;}    
}

and then do the deserialization.

But I think that is an unnecessary defining a class so isn't there a way to directly convert json array to c# string array

Thanks in advance.

2 Answers 2

5

Figure it out!

Using stringified array object rather than direct named json parameter to pass as data solved my problem

I am now posting like this

var Ids = new Array();
Ids.push("Team1");
Ids.push("Team2");

$.post(url, JSON.stringify(Ids), function(response) {}, 'json');

And now able to deserialize json response directly to string array like this

string jsonData = new StreamReader(context.Request.InputStream).ReadToEnd();
var selectedTeams = new JavaScriptSerializer().Deserialize<string[]>(jsonData);

Thanks!!

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

Comments

1

you could develop your own class, but I would suggest you use this: http://json.codeplex.com/

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.