0

I have some Properties and i want to save some specific property value in json format.Here is my code and i want to save two properties value like SelectedScalesModel and SelectedScales port Can anyone help me with this.

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");
    }
}
  • can you please explain which part of your code has issues? it seems to write json to file. – ASh Aug 20 '18 at 11:06
  • @ASh It Doesn't save to Json file as there is a RelayCommand property and i also dont want to save that. I want to save only two property values which is mentioned above – Shanto Siddiq Aug 20 '18 at 11:26
  • 1
    Possible duplicate of [How to exclude property from Json Serialization](https://stackoverflow.com/questions/10169648/how-to-exclude-property-from-json-serialization) – Tom Doodler Aug 20 '18 at 11:29

1 Answers1

1

You can try to SerializeObject by anonymous class then carry your expect property instead of SetUpViewModel object.

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");
}

Note

use this because your property info in your object.

D-Shih
  • 44,943
  • 6
  • 31
  • 51