8

I have the following simple class:

public class Test
{
    public string property1 { get; set; }
    public string property2 { get; set; }
}

When I try to serialize it into JSON using:

Test t = new Test() { property1 = "p1", property2 = "p2" };
var serializedData = JsonConvert.SerializeObject(t, Formatting.None);

I get JSON that looks like the following:

enter image description here

This will come across as null when I try to submit it to a WEB API app. I am using the application/json in the content header.

If I instead submit the same class starting off as a string, it works fine:

string test = "{\"property1\":\"p1\",\"property2\":\"p2\"}";
var serializedData = JsonConvert.SerializeObject(test, Formatting.None);

But it looks like this in the Visualizer:

enter image description here

If I paste both strings into Notepad, they look exactly the same.

Any ideas why the class serialization doesn't work?

4thSpace
  • 43,672
  • 97
  • 296
  • 475
  • Are you returning this from API controller or you are posting it from Java Script? When returning string from the controller and treating it as json can cause trouble unless you explicitly set content type. Can you post your controller code? – Sanjay Singh May 13 '15 at 03:09
  • Visual Studio may be confusing things with too-clever escaping. To see the actual contents of the strings, in Immediate Window type `Debug.WriteLine(serializedData)`. You will see that the first is a JSON object with two properties, the second is a JSON string whose content is a JSON object that has been escaped into a string literal. As to why the first case comes across as null on the server, can you share the code that makes the call? – dbc May 13 '15 at 06:57
  • How are you exactly submitting it to WebAPI? – Konamiman May 13 '15 at 07:55
  • I'm using the WebClient Upload method to submit and setting it to POST. – 4thSpace May 14 '15 at 03:10

1 Answers1

1

The JSON serialization works fine. In the first case when you're serializing the object it returns you normal JSON:

{
    "property1": "p1",
    "property2": "p2"
}

In the second case you have already serialized the JSON by hand and you're trying to serialize it second time which is resulting in a new JSON containing a JSON itself as single value or more likely single key:

{ "{\"property1\":\"p1\",\"property2\":\"p2\"}" }

You can test that the second string is already serialized by running this code:

var serializedData2 = JsonConvert.DeserializeObject(test);

And it should return you the key-values of the JSON:

{
    "property1": "p1",
    "property2": "p2"
}

I guess the null value is coming from somewhere else.

Itay Grudev
  • 7,055
  • 4
  • 54
  • 86
nikitz
  • 1,051
  • 2
  • 12
  • 35