如何以json格式写入特定的C#属性值?

时间:2018-08-20 11:04:28

标签: c# json wpf mvvm

我有一些属性,我想以json格式保存一些特定的属性值。这是我的代码,我想保存两个属性值,如SelectedScalesModel和SelectedScales port有人可以帮我吗?

public class SetUpViewModel : ViewModelBase
{
    public List<string> ScalesModel { get; set; } = new List<string> { "None", "METTLER-TOLEDO", "DINI ARGEO DFW-DFWK", "ESSAE SI-810" };
    private string _selectedScalesModel;

    public string SelectedScalesModel
    {
        get { return _selectedScalesModel; }
        set
        {
            _selectedScalesModel = value;
            RaisePropertyChanged("SelectedScalesModel");
        }
    }

    public List<string> ScalesPort { get; set; } = new List<string> { "None", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "COM10", "COM11", "COM12", "COM13", "COM14", "COM15" };
    private string _selectedScalesPort;

    public string SelectedScalesPort
    {
        get { return _selectedScalesPort; }
        set
        {
            _selectedScalesPort = value;
            RaisePropertyChanged("SelectedScalesPort");
        }
    }
    string _text1;

    public string BlackLineText
    {
        get { return _text1; }
        set
        {
            _text1 = value;
            RaisePropertyChanged(nameof(BlackLineText));
        }
    }
    public RelayCommand SaveButtonCommand { get; private set; }
    public SetUpViewModel()
    {
        SaveButtonCommand = new RelayCommand(SaveCommand);
    }
    private void SaveCommand()
    {
        SetUpViewModel setUpobj = new SetUpViewModel();
        string strJsonResult = JsonConvert.SerializeObject(setUpobj);
        File.WriteAllText("setup.json", strJsonResult);
        MessageBox.Show("File save in Json Format");
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试通过匿名类SerializeObject,然后携带您的Expect属性而不是SetUpViewModel对象。

private void SaveCommand()
{
    string strJsonResult = JsonConvert.SerializeObject(
        new {
            SelectedScalesModel = this.SelectedScalesModel,
            SelectedScalesPort = this.SelectedScalesPort
        }
    );
    File.WriteAllText("setup.json", strJsonResult);
    MessageBox.Show("File save in Json Format");
}

注意

使用this是因为您的属性信息在对象中。