4

I have the following json being sent to api

{
     "Id":22,
     "UserId":22,
     "Payload":{
        "Field":"some payload value"
        ...more unknown field/values go here
     },
     "ContextTypeId":1,
     "EventTypeId":1,
     "SessionId":1
}

I would like to map it to the following:

  public class CreateTrackItem : IRequest<int>
    {  
        public int Id { get; set; }
        public int UserId { get; set; }

        public string Payload { get; set; }
        public int ContextTypeId { get; set; }
        public int SessionId { get; set; }
        public int EventTypeId { get; set; }
    }

When mapped the Payload property fails that it cannot map json to string, i simply want the Payload to be a string version of the json (will go into a jsonb field in postgres)

I am using .NET Core 3.0 and prefer to use the built in System.Text.Json if possible before switching to Newtonsoft.

dbc
  • 104,963
  • 20
  • 228
  • 340
Zoinky
  • 4,083
  • 11
  • 40
  • 78
  • `Payload` needs to be a `class` object with `property` `Field`. `"Payload":{ "Field":"some payload value" },` This is a complex object, not a string. – Ryan Wilson Oct 29 '19 at 20:20
  • @RyanWilson since the payload structure is unknown, other than that it will be valid json, its impossible to construct a class, that is why the property is set to be a string which will take what ever json is thrown at it – Zoinky Oct 29 '19 at 20:25
  • Then you either need to write a custom `JSON Converter` or try using type `JToken`, please see this post (https://stackoverflow.com/questions/29980580/deserialize-json-object-property-to-string) – Ryan Wilson Oct 29 '19 at 20:26

2 Answers2

9

If you are using asp.net core 3.0 (or System.Text.Json with .Net 6) then this has built-in JSON support. I have used the following and it works without setting the custom input handler.

//// using System.Text.Json;

[HttpPost]
public async Task<IActionResult> Index([FromBody] JsonElement body)
{

    string json = System.Text.Json.JsonSerializer.Serialize(body);
    return Ok();

}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
ameya
  • 1,448
  • 1
  • 15
  • 31
0

You can use Object type instead of string. Or use JToken type from Newtonsoft as Ryan already commented above.

public object Payload { get; set; }

 public class CreateTrackItem : IRequest<int>
{  
    public int Id { get; set; }
    public int UserId { get; set; }

    public object Payload { get; set; }
    public int ContextTypeId { get; set; }
    public int SessionId { get; set; }
    public int EventTypeId { get; set; }
}
kode_anil
  • 66
  • 1
  • 6