0

I want to make a formatted json file in C#.

I want to make like this:

{
    "LiftPositioner" : [
        "LiftMax" : 5,
        "LiftMin" : 0
    ], 

    "Temperature" : [
        "CH0_Temp" : 25,
        "CH1_Temp" : 25
    ]
}

but the result was

{
 "LiftMax": 5,
 "LiftMin": 0,
 "CH0_Temp": 25,
 "CH1_Temp": 25
}

This is my code :

var json = new JObject();
json.Add("LiftMax", Convert.ToInt32(radTextBox_LiftMax.Text));
json.Add("LiftMin", Convert.ToInt32(radTextBox_LiftMin.Text));

json.Add("CH0_Temp", Convert.ToInt32(radTextBox_CH0.Text));
json.Add("CH1_Temp", Convert.ToInt32(radTextBox_CH1.Text));

string strJson = JsonConvert.SerializeObject(json, Formatting.Indented);
File.WriteAllText(@"ValueSetting.json", strJson);

What do I have to change in code?

1
  • Should the values of LiftPositioner and Temperature be lists? Commented Jun 5, 2019 at 0:56

1 Answer 1

1

If you're going to be running JsonConvert.SerializeObject anyways, you may have an easier go of it by just creating an anonymous type with your values. The following would get you your desired result:

var item = new
{
    LiftPositioner = new[] 
    { 
        new 
        {
            LiftMax = 5,
            LiftMin = 0
        }
    },
    Temperature = new[] 
    {
        new
        {
            CH0_Temp = 25,
            CH1_Temp = 25
        }
    }
};
string strJson = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(strJson);

Which outputs the following:

{
  "LiftPositioner": [
    {
      "LiftMax": 5,
      "LiftMin": 0
    }
  ],
  "Temperature": [
    {
      "CH0_Temp": 25,
      "CH1_Temp": 25
    }
  ]
}

If you don't want lists for the LiftPositioner and Temperature properties, you could reduce this down to:

var item = new
{
    LiftPositioner = 
    new 
    {
        LiftMax = 5,
        LiftMin = 0
    },
    Temperature = 
    new
    {
        CH0_Temp = 25,
        CH1_Temp = 25
    }
};

Which would yield

{
  "LiftPositioner": {
    "LiftMax": 5,
    "LiftMin": 0
  },
  "Temperature": {
    "CH0_Temp": 25,
    "CH1_Temp": 25
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.