C# JSON字符串生成怎么写比较优雅

不多说废话了,直接贴代码。

直接将对象转成JSON字符串,这种个人觉的比起拼接字符串看起来优雅,且出错率更低些。

            var rule = new {
                pa_sscan = new {
                    beam_num = 128,
                    probe_connection_pos = 0,
                    linear_pa_probe = new
                    {
                        elm_num = 16,
                        pitch = 2.0
                    },
                    slope_wedge = new
                    {
                        angle = 37.0,
                        height = 20.0
                    },
                    workpiece = new
                    {
                        sound_velocity = 5900.0
                    }
                }
            };

            // 序列化对象为JSON字符串,使用自定义选项
            string jsonString = JsonConvert.SerializeObject(rule);
            Console.WriteLine(jsonString);

出来的JSON字符串格式

{
  "pa_sscan": {
    "beam_num": 128,
    "probe_connection_pos": 0,
    "linear_pa_probe": {
      "elm_num": 16,
      "pitch": 2
    },
    "slope_wedge": {
      "angle": 37,
      "height": 20
    },
    "workpiece": {
      "sound_velocity": 5900
    }
  }
}

 

 

另外再看一个显例,复杂点的,传输的参数里面数组,再带数组的写法

            var json = new
            {
                pa_sscan = new
                {
                    beam_num = 128,
                    probe_connection_pos = 0,
                    linear_pa_probe = new
                    {
                        elm_num = 16,
                        pitch = 2.0
                    },
                    slope_wedge = new
                    {
                        angle = 37.0,
                        height = 20.0
                    },
                    workpiece = new
                    {
                        sound_velocity = 5900.0
                    },
                    myarry = new Array[4],
                }
            };

            json.pa_sscan.myarry[0] = new int[] { 0, 16 };
            json.pa_sscan.myarry[1] = new int[] { 0, 15 };
            json.pa_sscan.myarry[2] = new int[] { 0, 14 };
            json.pa_sscan.myarry[3] = new int[] { 0, 13 };


            //object xx = new object[4] { json, json, json, json };

            // 序列化对象为JSON字符串,使用自定义选项
            string jsonString = JsonConvert.SerializeObject(json, Formatting.Indented);
            Console.WriteLine(jsonString);

输出的参数

{
  "pa_sscan": {
    "beam_num": 128,
    "probe_connection_pos": 0,
    "linear_pa_probe": {
      "elm_num": 16,
      "pitch": 2.0
    },
    "slope_wedge": {
      "angle": 37.0,
      "height": 20.0
    },
    "workpiece": {
      "sound_velocity": 5900.0
    },
    "myarry": [
      [
        0,
        16
      ],
      [
        0,
        15
      ],
      [
        0,
        14
      ],
      [
        0,
        13
      ]
    ]
  }
}

  

 

 

posted @ 2025-09-24 09:23  春天又来了  阅读(13)  评论(0)    收藏  举报