将C#类转换为Json

时间:2017-10-25 22:13:29

标签: c# json

如何使用多个c#类序列化为一个json字符串。能够使json数据中的变量保持可以更改的值

string outputJSON = JsonConvert.SerializeObject();

我有以下课程

 public class Rootobject
    {
    public string Number { get; set; }
        public string RequestedDeviceType { get; set; }
        public string DeliveryMethod { get; set; }
        public Customer Customer { get; set; }
        public Vehicle Vehicle { get; set; }
    }

    public class Customer
    {
        public Contacts Contacts { get; set; }
        public string Name { get; set; }
        public string Number { get; set; }
        public bool OverrideData { get; set; }
    }

    public class Contacts
    {
        public string FirstName { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string City { get; set; }
        public string Address { get; set; }
        public string MobilePhone { get; set; }
    }

    public class Vehicle
    {
        public string VIN { get; set; }
        public string MakeModelCode { get; set; }
        public string LicensePlate { get; set; }
        public string Make { get; set; }
        public string Model { get; set; }
        public int YearOfInitialRegistration { get; set; }
        public string MotorType { get; set; }
        public bool OverrideData { get; set; }
    }

}

他们必须序列化到json结构的以下结构,我必须能够捕获用户输入并将值设置为json文件

{
  "Number": "xTest",
  "RequestedDeviceType": "XXXX",
  "DeliveryMethod": "XXXX",
  "Customer": {
    "Contacts": {

      "FirstName": "John",
      "Name": "Doe",
      "Email": "mail@demo.com",
      "City": "Harare",
      "Address": "XXXXX",
      "MobilePhone": "00000000"

    },
    "Name": "Peter Chaneta",
    "Number": "4567865678",
    "OverrideData": true
  },
  "Vehicle": {
    "VIN": "weryts55444554",
    "MakeModelCode": "34010",
    "LicensePlate": "SS 100 GP",
    "Make": "RANGE ROVER",
    "Model": "SPORT",
    "YearOfInitialRegistration": 2016,
    "MotorType": "Petrol",
    "OverrideData": true
  }
}

3 个答案:

答案 0 :(得分:2)

我猜您正在使用JSON.net。 如果没有,你可以通过Nuget-Packet Manager获得它。

你打电话给你的班级“联系人”你想要多个联系人吗?如果是,您可能希望在RootObject上使用List。

现在,如果您使用:

#include "main.hpp"

bool Ini::Load(std::string path)
{
    std::ifstream input;

    input.open(path.c_str(), std::ios::binary);

    if (!input.is_open())
        return false;

    Load(input);

    input.close();

    return true;
}

void Ini::Load(std::istream& input)
{
    std::vector<IniSection>::iterator section;
    std::string lineValue;

    enum
    {
        KEY,
        SECTION,
        COMMENT,
        OTHER
    };

    while (getline(input, lineValue))
    {
//      TrimLeft(lineValue);
//      TrimRight(lineValue, "\n\r");

        if (!lineValue.empty())
        {
            unsigned int type = OTHER;

            type = (lineValue.find_first_of("[") == 0 && (lineValue[lineValue.find_last_not_of(" \t\r\n")] == ']')) ? SECTION : OTHER;
            type = ((type == OTHER) && (lineValue.find_first_of("=") != std::string::npos && lineValue.find_first_of("=") > 0)) ? KEY : type;
            type = ((type == OTHER) && (lineValue.find_first_of("#") == 0)) ? COMMENT : type;

            switch (type)
            {
            case SECTION:
                section = AddSection(lineValue.substr(1, lineValue.size() - 2));
                break;
            case KEY:
                {
                    size_t equalSpot = lineValue.find_first_of("=");
                    std::string keyName = lineValue.substr(0, equalSpot);
                    std::string keyValue = lineValue.substr(equalSpot + 1);
                    std::vector<IniKey>::iterator key = section->AddKey(keyName);
                    key->SetValue(keyValue);
                    break;
                }

            default:
                break;
            }
        }
    }
}

void Ini::Create(std::string path)
{
    std::fstream file;

    file.open(path, std::fstream::out);

    file.close();
}

bool Ini::Save(std::string path)
{
    std::ofstream output;

    output.open(path.c_str(), std::ios::binary);

    if (!output.is_open())
    {
        output.close();

        return false;
    }

    Save(output);

    output.close();

    return true;
}

void Ini::Save(std::ostream& output)
{
    std::string section;
    std::vector<IniSection>::iterator iter1;

    for (iter1 = Sections.begin(); iter1 != Sections.end(); iter1++)
    {
        section = "[" + iter1->GetSectionName() + "]";

        output << section << "\r\n";

        std::vector<IniKey>::iterator iter2;

        for (iter2 = iter1->Keys.begin(); iter2 != iter1->Keys.end(); iter2++)
        {
            std::string comment = "# " + iter2->GetComment();

            if (comment != "# ")
                output << comment << "\r\n";

            std::string key = iter2->GetKeyName() + "=" + iter2->GetValue();

            output << key << "\r\n";
        }

        output << "\r\n";
    }
}

std::string Ini::GetKeyValue(std::string section, std::string key)
{
    if (hasSection(section))
    {
        auto s = GetSection(section);
        if (s->hasKey(key))
        {
            return s->GetKey(key)->GetValue();
        }
    }
    return std::string();
}

void Ini::SetKeyValue(std::string section, std::string key, std::string value)
{
    if (hasSection(section))
    {
        auto s = GetSection(section);
        if (s->hasKey(key))
        {
            s->GetKey(key)->SetValue(value);
        }
    }
}

// IniSection -----------------------------------------------------------------------------------

IniSection::IniSection(Ini& ini, const std::string& section) : pIni(ini), sectionName(section)
{

}

void Ini::RemoveAllSections()
{
//  std::vector<IniSection *>::iterator iter;

//  for (iter = Sections.begin(); iter != Sections.end(); iter++)
//      delete *iter;

    Sections.clear();
}

std::vector<IniSection>::iterator Ini::FindSection(const std::string& section)
{
    IniSection tempSection(*this, section);

    return std::find(Sections.begin(), Sections.end(), tempSection);
}

std::vector<IniSection>::iterator Ini::AddSection(const std::string& section)
{
    std::vector<IniSection>::iterator iter = FindSection(section);

    if (iter == Sections.end())
    {
        Sections.emplace_back(*this, section);

        return Sections.end() - 1;
    }
    else
        return iter;
}

std::vector<IniSection>::iterator Ini::GetSection(const std::string& section)
{
    return FindSection(section);
}

std::string IniSection::GetSectionName()
{
    return sectionName;
}

std::string IniSection::GetKeyValue(const std::string& key)
{
    if (hasKey(key))
    {
        return GetKey(key)->GetValue();
    }
    return std::string();
}

void IniSection::SetKeyValue(const std::string& key, const std::string& value)
{
    if (hasKey(key))
        GetKey(key)->SetValue(value);
}

// IniKey -----------------------------------------------------------------------------------

void IniSection::RemoveAllKeys()
{
    //  std::vector<IniKey *>::iterator iter;

    //  for (iter = Keys.begin(); iter != Keys.end(); iter++)
    //      delete *iter;

    // std::vector manages the allocations automatically
    // as long as you are not using raw pointers
    Keys.clear();
}

std::vector<IniKey>::iterator IniSection::FindKey(const std::string& key)
{
    IniKey tempKey(*this, key);
    return std::find(Keys.begin(), Keys.end(), tempKey);
}

std::vector<IniKey>::iterator IniSection::AddKey(const std::string& key)
{
    if (hasKey(key))
    {
        return GetKey(key);
    }
    else
        return Keys.insert(Keys.end(), {*this, key});
}

bool IniSection::hasKey(const std::string& key)
{
    return FindKey(key) != Keys.end();
}

void IniKey::SetValue(std::string value)
{
    keyValue = value;
}

std::string IniKey::GetValue()
{
    return keyValue;
}

std::string IniKey::GetKeyName()
{
    return keyName;
}

std::vector<IniKey>::iterator IniSection::GetKey(const std::string& key)
{
    if (hasKey(key))
        return GetKey(key);

    return Keys.end();
}

bool Ini::hasSection(const std::string& section)
{
    return FindSection(section) != Sections.end();
}

void IniKey::AddComment(std::string comment)
{
    commentValue = comment;
}

std::string IniKey::GetComment()
{
    return commentValue;
}


int main()
{
    // How i want to use it:
    // Write:
    Ini ini;

    ini.Create(IniPath);

    ini.Load(IniPath);

    // Check if "Test" section exists and add it if it doesn't
    if (!ini.hasSection("Test"))
    {
        ini.AddSection("Test");
    }

    auto secTest(ini.GetSection("Test"));
    secTest->AddKey("Key1")->SetValue("KeyValue1");
    secTest->GetKey("Key1")->AddComment("This is a Test");

    ini.Save(IniPath);

    // Read:
    Ini ini1;

    ini1.Load(IniPath);

//  IniSection *Section = ini.GetSection("Test");

    if (ini1.hasSection("Test"))
    {
        if (ini1.GetSection("Test")->hasKey("Key1"))
        {
            std::string keyValue = ini.GetSection("Test")->GetKeyValue("Key1");
        }
    }

    return 0;

}

您可以按要求在字符串中包含所有数据。从这里你可以把它写到一个文件。 如果您想要更改数据并再次阅读,您可以使用以下内容:

var data = new Rootobject();
var dataString = JsonConvert.SerializeObject(data);

现在您可以在某处显示数据,或者可以通过任何输入控件更改数据。 (网站/ Windows窗体/ XAML /控制台......)

您可以在json.net(https://www.newtonsoft.com/json

的官方文档中找到其他任何内容

否则你的问题太过泛泛了。

答案 1 :(得分:0)

作为JSON.Net的替代方案,您还可以使用System.Web.Extensions命名空间中的一个:

using System.Web.Extensions;


public string SerializeClassToJSON(object baseClass)
{
    var jSerializer = new JavascriptSerializer();
    var jsonString = jSerializer.Serialize(baseClass);

    return jsonString;
}

答案 2 :(得分:0)

如果您可以在线与第三方分享您的课程,您可以使用以下链接直接从课程中生成 JSON。

C# to JSON