Home > Net >  JArray Strings to JArray of Objects
JArray Strings to JArray of Objects

Time:05-02

I am trying to add a JArray towards a Jobject that is created manually and using that JObject to do a Put API Call.

The JArray I get is the below:

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

As you can see, the Jarray is holding strings, however I want it to hold JObjects.

I have a function that accepts a JSON string and modifies the String.

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

To which I am doing the below to make an API call.

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);


}

The end result i would like is like below:

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

CodePudding user response:

From this line, you are adding the Object as string to JArray.

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

You should use JObject.FromObject() to cast to JObject.

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

And for the foreach part, you can work with 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

CodePudding user response:

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

I just parsed the data as a JOject instead of a serialized JSON this got me what i needed

  • Related