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?
JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.
The two primary parts that make up JSON are keys and values. Together they make a key/value pair. Key: A key is always a string enclosed in quotation marks. Value: A value can be a string, number, boolean expression, array, or object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With