在 C# 中将变量添加到 json 字符串

Add variable to json string in c#

我正在尝试调用图表 api,需要一些帮助来检查这个

string addItemJsonString = "{\"fields\":{\"ID\":\"" + ID + "\",\"DeviceName\":\"" + deviceName + "'}\"}";

这是我的json,我需要将它们转换成字符串

{
   "fields":{
      "ID": ID,
      "Device Name": deviceName
   }
}

图表 API:https://docs.microsoft.com/en-us/graph/api/listitem-create?view=graph-rest-1.0&tabs=csharp

你的问题不够明确。但是如果我理解正确的话你想转换这个 json

{
   "fields":{
      "ID": ID,
      "Device Name": deviceName
   }
}

转换成字符串。

我强烈建议您使用序列化库,不要自己编写 json。您可以轻松创建 class 或字典并将其序列化为 json.

但是如果你坚持认为你的 json 字符串中有两个错误。

1- 在 deviceName 之后,您使用 ' 而不是 "

2- 您在最后一个 } 之前添加了额外的 "

所以正确的json应该是这样的

string addItemJsonString = "{\"fields\":{\"ID\":\"" + ID + "\",\"DeviceName\":\"" + deviceName + "\"}}";

使用插值

$"{{\"fields\":{{\"ID\":\"{ID}\",\"DeviceName\":\"{deviceName}\"}}}}";

但最好创建一个 DTO class 并将其序列化为 JSON。

public class MyDto
{
    [JsonProperty("fields")]
    public FieldDto Fields { get; set; }
}

public class FieldDto
{
    [JsonProperty("ID")]
    public int Id { get; set; }

    [JsonProperty("Device name")]
    public string DeviceName { get; set; }
}

public static Main(string[] args)
{
    int id = 1;
    string deviceName = "Phone";

    var blee = new MyDto
    {
        Fields = new FieldDto
        {
            Id = id,
            DeviceName = deviceName
        }
    }

    string json = JsonConvert.SerializeObject(blee);
}

对于序列化,使用 Newtonsoft 库 https://www.newtonsoft.com/json/help/html/SerializeWithJsonConverters.htm

您似乎在询问有关在 C# 中格式化 json 的问题。

  1. 使用 Newtonsoft.Json 序列化程序和 匿名对象(方便且推荐,因为更通用且更不容易出错)
using Newtonsoft.Json;

var obj = new { fields = new { ID = ID, DeviceName = deviceName } };
string jsonString = JsonConvert.SerializeObject(obj);
  1. 直接字符串操作(您需要自己处理 json 格式化!)。例如。字符串必须始终封装在双引号中,并且如果它存在于其值
  2. 内,则需要确保对它们进行转义
Debug.Assert(!ID.Contains('"'));
Debug.Assert(!deviceName.Contains('"'));
string addItemJsonString = $"{{\"fields\":{{\"ID\":\"{ID}\",\"DeviceName\":\"{deviceName}\"}}\"}}";