2

There is a similar question with the same title, but the solution is not valid for my problem.

I'm trying to serialize the following JSON:

{"Id":1,
 "Questions":
    [{"Id":"q-1-Q0001","Text":"Volume Too High"},
     {"Id":"q-1-Q0002","Text":"Volume Too Low"}],
 "Text":"My text."}

With this structure in my C#:

public class Issue
{
    public Issue() { Questions = new List<Question>(); }
    public string Id { get; set; }
    public List<Question> Questions { get; set; }
    public string Text { get; set; }
}

public class Question
{
    public string Id { get; set; }
    public string Text { get; set; }
}

I have JavaScript send a POST with the JSON above to this C# function:

public JsonResult AddIssueToQueue(Issue issue)
{
    var id = issue.Id; // Set correctly
    var text = issue.Text; // Set correctly
    var q = issue.Questions; // NOT set correctly. Set to List of two empty Question items.
}

id and text are set correctly, but q is set to a List that contains two empty Question objects (Id and Text are null in each).

Is my JSON formatted incorrectly? Why doesn't the Questions array propagate correctly?

Suman Banerjee
  • 1,923
  • 4
  • 24
  • 40
Paul
  • 402
  • 4
  • 12
  • Are `issue.Id` and `issue.Text` set correctly? – Marcelo Cantos Jun 23 '11 at 00:17
  • Yes. id and text (issue.Id and issue.Text) hold the correct values. – Paul Jun 23 '11 at 00:18
  • I doubt this is it, but when I serialize your Issue class using the JavaScriptSerializer it puts quotes around the 1 for Issue ID, i.e. `{"Id":"1",`. However, I can deserialize with or without the quotes. – rsbarro Jun 23 '11 at 01:53
  • The serialization happens automatically. The AddIssueToQueue class is called via `POST` by JavaScript, so I don't know how I'd set parameters. – Paul Jun 23 '11 at 14:29

2 Answers2

0

This is a just a wild guess, but your JSON structure has an ID with an integer, as rsbarro mentioned above. But your proxy class in C# is expecting a string - is it possible the type conversion is getting mixed up there?

Justin Beckwith
  • 7,686
  • 1
  • 33
  • 55
0

This my ajax call and it is working fine I am getting the question List

   $.ajax({
                type: 'POST',
            contentType: 'application/json; charset=utf-8',
            data: "{'issue':{'Id':1,'Questions':[{'Id':'q-1-Q0001','Text':'Volume Too High'},{'Id':'q-1-Q0002','Text':'Volume Too Low'}],'Text':'My text.'}}" ,

            dataType: 'html',
            url: 'AddIssueToQueue',
            success: function (data) {
                if (data) {
                    //Do something 
                }
            }
        });

Can you share your code as well.

Nikshep
  • 2,117
  • 4
  • 21
  • 30