JArray 字符串到 JArray 的对象

JArray Strings to JArray of Objects

我正在尝试将 JArray 添加到手动创建的 Jobject 并使用 JObject 进行看跌 API 看涨。

我得到的JArray如下:

[
  "{\"name\":\"route4\",\"properties\":{\"addressPrefix\":\"104.0.3.0/24\",\"nextHopType\":\"VnetLocal\"}}",
  "{\"name\":\"route5\",\"properties\":{\"addressPrefix\":\"105.0.3.0/24\",\"nextHopType\":\"VnetLocal\"}}"
]

如您所见,Jarray 包含字符串,但我希望它包含 JObjects.

我有一个接受 JSON 字符串并修改字符串的函数。

public static JArray GetListofRoutesFromTable(string jsonRT)
{
    JObject jo = JObject.Parse(jsonRT);
    JObject properties = (JObject)jo["properties"];
    var surveytrackingA = new JArray();
    JArray item = (JArray)properties["routes"];
    item.Remove("id");
    item.Remove("etag");
    foreach (var items in item)
    {
        if (items["properties"]["nextHopType"].ToString() == "Internet")
        {
        }
        else
        {
            /*
             * {
                "name": "route1",
                "properties": {
                  "addressPrefix": "101.0.3.0/24",
                  "nextHopType": "Internet"
                }
              }
             */
            var payload = new { name = items["name"].ToString(), properties = new { addressPrefix = items["properties"]["addressPrefix"].ToString(),
                nextHopType = items["properties"]["nextHopType"].ToString() } };
            surveytrackingA.Add(JsonConvert.SerializeObject(payload));
        }

    }
   return surveytrackingA;
}

我正在执行以下操作以拨打 API 电话。

public async void updateOrCreateRouteTableWithRoutes(string id, JArray routes, string location = "australiasoutheast")
{
    Console.WriteLine(routes);
    var payload = new { properties = new { }, location = location, tags = new { FWaaSAzured = "GatewaySubnetRoute" } };
    var jsonToReturn = JsonConvert.SerializeObject(payload);
    string jsonPayload = jsonToReturn.ToString();
    JObject JOpayload = JObject.Parse(jsonPayload);
    JOpayload["properties"]["routes"] = routes;
    var PayloadObject = JsonConvert.SerializeObject(JOpayload);
    Console.WriteLine(PayloadObject.ToString());
    using var client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", this.token);
    char[] charsToTrimStart = { '/', 's', 'u', 'b', 's', 'c', 'r', 'i', 'p', 't', 'i', 'o', 'n', 's', '/' };
    string idTrimmed = id.TrimStart(charsToTrimStart);
    string sendUrl = baseurl + idTrimmed + "?api-version=2021-04-01";
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, sendUrl)
    {
        Content = new StringContent(PayloadObject.ToString(), Encoding.UTF8, "application/json"),
    };
    HttpResponseMessage response = await client.SendAsync(request);
    string responseContent = await response.Content.ReadAsStringAsync();
    Console.WriteLine(responseContent);


}

我想要的最终结果如下:

{"properties":{"routes":[{"name":"route4","properties":{"addressPrefix":"104.0.3.0/24","nextHopType":"VnetLocal"}},{"name":"route5","properties":{"addressPrefix":"105.0.3.0/24","nextHopType":"VnetLocal"}}]},"location":"australiasoutheast","tags":{"FWaaSAzured":"GatewaySubnetRoute"}}
public static JArray GetListofRoutesFromTable(string jsonRT)
    {
        JObject jo = JObject.Parse(jsonRT);
        JObject properties = (JObject)jo["properties"];
        var surveytrackingA = new JArray();
        JArray item = (JArray)properties["routes"];
        item.Remove("id");
        item.Remove("etag");
        foreach (var items in item)
        {
            if (items["properties"]["nextHopType"].ToString() == "Internet")
            {
            }
            else
            {
                /*
                 * {
                    "name": "route1",
                    "properties": {
                      "addressPrefix": "101.0.3.0/24",
                      "nextHopType": "Internet"
                    }
                  }
                 
                var payload = new { name = items["name"].ToString(), properties = new { addressPrefix = items["properties"]["addressPrefix"].ToString(),
                    nextHopType = items["properties"]["nextHopType"].ToString() } };
                var jsonToReturn = JsonConvert.SerializeObject(payload);
                string jsonPayload = jsonToReturn.ToString();
                JObject JOpayload = JObject.Parse(jsonPayload);
                surveytrackingA.Add(JOpayload);
            }

        }
        return surveytrackingA;
    }

我只是将数据解析为 JOject 而不是序列化 JSON 这让我得到了我需要的东西

从这一行开始,您将对象作为字符串添加到 JArray

surveytrackingA.Add(JsonConvert.SerializeObject(payload));

您应该使用 JObject.FromObject() 转换为 JObject

surveytrackingA.Add(JObject.FromObject(payload));

对于 foreach 部分,您可以使用 LINQ a:s

IEnumerable<JObject> jObjs = item
    .Where(x => x["properties"]["nextHopType"].ToString() != "Internet")
    .Select(x => JObject.FromObject(new 
        { 
            name = x["name"].ToString(), 
            properties = new 
            { 
                addressPrefix = x["properties"]["addressPrefix"].ToString(),
                nextHopType = x["properties"]["nextHopType"].ToString()
            }
        })
    );
        
JArray surveytrackingA = JArray.FromObject(jObjs);

Sample program