What is the difference between these 2 JSON formats?

时间:2015-05-12 22:54:02

标签: c# json asp.net-mvc visual-studio

I have the following simple class:

reverse()

When I try to serialize it into JSON using:

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

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 Test t = new Test() { property1 = "p1", property2 = "p2" }; var serializedData = JsonConvert.SerializeObject(t, Formatting.None); in the content header.

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

application/json

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?

1 个答案:

答案 0 :(得分:1)

JSON序列化工作正常。在第一种情况下,当您序列化对象时,它会返回正常的JSON:

#include <iostream>

using namespace std;

class Student
{
private:
    int age;
public:
    Student() : age(0){}
    Student (int age1) : age(age1) {}
    void setAge(int value);
    int getAge(){return age;}
    void readFrom(istream& is);
};

istream& operator >> (istream &is, Student& a)
{
    a.readFrom(is);
    return is;
}

void Student::readFrom(istream& is){
    is >> age;
}

void Student::setAge(int value){
    age = value;
}

int main()
{
    Student a;
    int age;
    cout << "input age of the student: "<< endl;
    cin >> age;
    a.setAge(age);
    cout << "Age of Student is " << a.getAge() << "?";
}

在第二种情况下,您已经手动序列化了JSON并且您正在尝试第二次序列化它,这导致一个新的JSON包含一个JSON本身作为单个值或更可能是单个键:

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

您可以通过运行此代码来测试第二个字符串是否已经序列化:

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

它应该返回JSON的键值:

var serializedData2 = JsonConvert.DeserializeObject(test);

我猜空值来自其他地方。

相关问题