avdeveloper
avdeveloper

Reputation: 549

How to deserialize dynamic Json objects?

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

Upvotes: 2

Views: 9813

Answers (4)

Duck Ling
Duck Ling

Reputation: 2160

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

Upvotes: 0

Charlieface
Charlieface

Reputation: 72415

JsonSerializer.Deserialize<Dictionary<string,string[]>>(body, serializerOptions);

Upvotes: 1

Gerardo Garcia
Gerardo Garcia

Reputation: 176

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

Upvotes: 0

misticos
misticos

Reputation: 807

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.

Upvotes: 1

Related Questions