2

I am currently receiving the following JSON response from my api:

{"Lastname":["ERRLASTNAMEEMPTY"],"Firstname":["ERRFIRSTNAMEEMPTY"]}

Note that the above response is dynamic - i.e sometimes I can have FirstName, sometimes LastName, sometimes both. This response is based on the validation of data.

My question is - is there a way to deserialize this response using JsonSerializer.DeSerialize?

I have tried to use it like this but it does not work:

var errorBody = JsonSerializer.Deserialize<dynamic>(body, serializerOptions);
avdeveloper
  • 449
  • 6
  • 30
  • But it's not completely dynamic, right? Sometimes you have `Lastname`, sometimes you have `Firstname`, and you just need one or the other or both, right? – dbc Jan 13 '21 at 13:55
  • Also, `System.Text.Json` does not currently support deserializing to dynamic objects, see [Read value from dynamic property from json payload](https://stackoverflow.com/q/64036207/3744182). – dbc Jan 13 '21 at 15:10
  • Use ExpandoObject instead of dynamic – Gerardo Garcia Jul 16 '21 at 04:34

4 Answers4

1
JsonSerializer.Deserialize<Dictionary<string,string[]>>(body, serializerOptions);
Pang
  • 9,564
  • 146
  • 81
  • 122
Charlieface
  • 52,284
  • 6
  • 19
  • 43
1

You can work with dynamic JSON objects with JObject like that:

var data = JObject.Parse(body);

And later you are able to access values with data["Lastname"]?.Value<string>(); and such, the way you want.

misticos
  • 718
  • 5
  • 22
0
JsonSerializer.Deserialize<ExpandoObject>(body, serializerOptions);
Pang
  • 9,564
  • 146
  • 81
  • 122
Gerardo Garcia
  • 180
  • 1
  • 5
0
// introduce a dynamic object from a string :
// {"UrlCheckId":581,"Request":{"JobId":"a531775f-be19-4c78-9717-94aa051f6b23","AuditId":"b05016f5-51c9-48ba-abcc-ec16251439e5","AlertDefinitionId":108,"JobCreated":"2022-05-20T07:09:56.236656+01:00","UrlJobId":0,"BatchJobId":"e46b9454-2f90-407d-9243-c0647cf6502d"},"JobCreated":"2022-05-20T07:10:21.4097268+01:00"}
// ...The UrlCheckId is an int primitive and Request is our UrlCheckJobRequest object.

dynamic msg = JsonConvert.DeserializeObject(message);

// to access an int (primitive) property:
int id = msg.UrlCheckId;

// to access an object, you might have to serialize the request into a string first...
var r = JsonConvert.SerializeObject(msg.Request);

// ... and then deserialize into an object
UrlCheckJobRequest request = JsonConvert.DeserializeObject<UrlCheckJobRequest>(r);
Duck Ling
  • 1,577
  • 13
  • 20