Home > Back-end >  how to add Array of json object in .NET?
how to add Array of json object in .NET?

Time:12-29

I have two web Apis, i would like to consume the an api's endpoint from the other api but the body of this endpoint contains array of json object like this :

{
  "urlOrigin": "string",
  "urlCascade": [
    {
      "customerId": 0,
      "evenement": "string",
      "userId": 0,
      "targetItemId": 0,
      "expireAt": "2021-12-28T12:25:20.606Z"
    }
  ]
}

what i did is :

        public async Task<HttpResponseMessage> saveShortCodes([FromBody] ShortCode sh)
    {
 Dictionary<String, dynamic> header = new Dictionary<String, dynamic>();
        Dictionary<String, dynamic> request2 = new Dictionary<String, dynamic>();
        List<Dictionary<String, dynamic>> body = new List<Dictionary<String, dynamic>>();
        header.Add("urlOrigin", sh.urlOrigin);
        for(var i=0; i < sh.urls.Count; i  )
        {
            request2.Add("customerId", sh.urls[i].CustomerId);
            request2.Add("evenement", sh.urls[i].Evenement);
            request2.Add("userId", sh.urls[i].UserId);
            request2.Add("expireAt", sh.urls[i].ExpireAt);
            if(sh.urls[i].TargetItemId!=null)
                request2.Add("targetItemId", sh.urls[i].TargetItemId);
            body.Add(request2);
        }
        header.Add("urlCascade", body);
        var httpContent = new StringContent(header.ToString(), System.Text.Encoding.UTF8, "application/json");
        String uri = "http://myUrl/url/generateShortcodes";
        var response = client.PostAsync(uri, httpContent).GetAwaiter().GetResult();
        Console.Write("response "   response);
        return response;
        }

this is the structure of my body :

public class ShortCode
{
    public string urlOrigin { get; set; }
    public List<urlCascade> urls { get; set; }
    public ShortCode()
    {
    }
}


  public class urlCascade
    {
        public int CustomerId { get; set; }
        public String Evenement { get; set; }
        public int UserId { get; set; }
        public int? TargetItemId { get; set; }
        public DateTime ExpireAt { get; set; }
        public urlCascade()
        {
        }
    }

when i tried to consume the endpoint with as shown i get :

dbug: Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatter[1]
  JSON input formatter threw an exception.
  Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: S. Path '', line 0, position 0.
     at Newtonsoft.Json.JsonTextReader.ParseValue()
     at Newtonsoft.Json.JsonReader.ReadAndMoveToContent()
     at Newtonsoft.Json.JsonReader.ReadForType(JsonContract contract, Boolean hasConverter)
     at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonInputFormatter: Debug: JSON input formatter threw an exception.

It seems to be a json format problem or data format, that is why i am asking the right way to represent the body of the request in my controller.

CodePudding user response:

Like i said in the comments, you should really study tha basics of JSON, OOP and Serialization/Deserialization, your code is way off the .Net guidelines of good pratices. All you need is:

public async Task<HttpResponseMessage> SaveShortCodes([FromBody] ShortCode sh)
{
    return await client.PostAsync("http://myUrl/url/generateShortcodes", JsonConvert.SerializeObject(sh));
}

public class UrlCascade
{
    [JsonPropertyName("customerId")]
    public int CustomerId { get; set; }

    [JsonPropertyName("evenement")]
    public string Evenement { get; set; }

    [JsonPropertyName("userId")]
    public int UserId { get; set; }

    [JsonPropertyName("targetItemId")]
    public int TargetItemId { get; set; }

    [JsonPropertyName("expireAt")]
    public DateTime ExpireAt { get; set; }
}

public class ShortCode
{
    [JsonPropertyName("urlOrigin")]
    public string UrlOrigin { get; set; }

    [JsonPropertyName("urlCascade")]
    public List<UrlCascade> UrlCascade { get; set; }
}

CodePudding user response:

Use Newtonsoft.Json Library and change saveShortCodes method to :

public async Task<HttpResponseMessage> saveShortCodes([FromBody] ShortCode sh)
{
   var json = JsonConvert.SerializeObject(sh);
   var httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
   String uri = "http://myUrl/url/generateShortcodes";
   var response = client.PostAsync(uri, httpContent).GetAwaiter().GetResult();
   Console.Write("response "   response);
   return response;
}
  • Related