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

我有一些属性,我想以 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");

    }

}


MM们
浏览 160回答 1
1回答

炎炎设计

您可以尝试SerializeObject通过匿名类然后携带您的期望属性而不是SetUpViewModel对象。private void SaveCommand(){&nbsp; &nbsp; string strJsonResult = JsonConvert.SerializeObject(&nbsp; &nbsp; &nbsp; &nbsp; new {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SelectedScalesModel = this.SelectedScalesModel,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SelectedScalesPort = this.SelectedScalesPort&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; );&nbsp; &nbsp; File.WriteAllText("setup.json", strJsonResult);&nbsp; &nbsp; MessageBox.Show("File save in Json Format");}笔记使用this因为您的对象中的属性信息。
打开App,查看更多内容
随时随地看视频慕课网APP