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);
3
  • 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? Commented Jan 13, 2021 at 13:55
  • Also, System.Text.Json does not currently support deserializing to dynamic objects, see Read value from dynamic property from json payload. Commented Jan 13, 2021 at 15:10
  • Use ExpandoObject instead of dynamic Commented Jul 16, 2021 at 4:34

4 Answers 4

1
JsonSerializer.Deserialize<Dictionary<string,string[]>>(body, serializerOptions);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

0
JsonSerializer.Deserialize<ExpandoObject>(body, serializerOptions);

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.