Jon Wells
Jon Wells

Reputation: 4259

Parsing JSON in C#

I have a JSON string that I am sending to a c# server. It comprises an array of Event objects and an Array of relationship objects. The relationship objects describe the database table relationships.

However I'm having trouble getting data from the the JSON at the server. The object doesn't exist on the server to deserailize into and JSON.net throws parse errors when I try the following:

// Both throw parse errors
JObject o = JObject.Parse(Request.Form.ToString());
JsonConvert.DeserializeObject<MobileEvents>(Request.Form.ToString());

the JSON:

{
    "CreateEvents": {
        "Event": [
            {
                "Id": "1",
                "Subject": "Hire a Clown"
            }
        ],
        "Relationship": [
            {
                "Primary": "Table1",
                "Secondary": "Table2",
                "Field": [
                    {
                        "Table1Id": "1",
                        "Table2Id": [
                            "101"
                        ]
                    }
                ]
            },
            {
                "Primary": "Table1",
                "Secondary": "Table3",
                "Field": [
                    {
                        "Table1Id": "1",
                        "Table3Id": [
                            "200025"
                        ]
                    }
                ]
            },
            {
                "Primary": "Table1",
                "Secondary": "Table4",
                "Field": [
                    {
                        "Table1Id": "1",
                        "Table4Id": [
                            "3"
                        ]
                    }
                ]
            }
        ]
    }
}

Upvotes: 0

Views: 4272

Answers (2)

user57508
user57508

Reputation:

I think you have an error within your getting ...

It's not

this.Request.Form.ToString(); // see http://stackoverflow.com/questions/7065979/why-is-the-return-value-of-request-form-tostring-different-from-the-result-of for output

Instead it should be

this.Request.Form["myInputNAME"].ToString();

Important - really use the name-attribute of your input/select/...-element

Anyways: I would like to encourage you, to use eg. <asp:HiddenField runat="server" ID="foo" />. When you have a server-control you can then access its value by simple doing this.foo.Value at server-side, whereas at client-side you can access the input field like document.getElementById('<%= this.foo.ClientID %>')

Upvotes: 2

Jeffrey Zhao
Jeffrey Zhao

Reputation: 5023

Request.Form.ToString() would returns the result like "a=1&b=3", it's definitely not what you need.

If you're passing values as submiting a form, you can use Request.Form["your-key"] to get the value.

If you're passing values by the http body, you can use new StreamReader(Request.InputStream).ReadToEnd() to get the whole JSON string.

Upvotes: 3

Related Questions