Reputation: 44352
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:
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:
If I paste both strings into Notepad, they look exactly the same.
Any ideas why the class serialization doesn't work?
Upvotes: 8
Views: 136
Reputation: 1091
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.
Upvotes: 1