Jacob
Jacob

Reputation: 101

how can i make formatted json file in c#

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?

Upvotes: 0

Views: 282

Answers (1)

Jonathon Chase
Jonathon Chase

Reputation: 9704

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
  }
}

Upvotes: 1

Related Questions