Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between these 2 JSON formats?

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?

like image 366
4thSpace Avatar asked May 12 '15 22:05

4thSpace


People also ask

What is the difference between JSONObject and JSONArray?

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.

What are the two parts of JSON?

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.


1 Answers

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.

like image 80
nikitz Avatar answered Nov 03 '22 09:11

nikitz