Add JsonObject to JsonArray with AOT

1 week ago 7
ARTICLE AD BOX

The warning here is bogus. It arises specifically because JsonNode.Add() has two overloads:

JsonArray.Add(JsonNode? item).

This adds a JsonNode to the array and does not require reflection. No AOT warnings will be emitted if you call this method.

JsonArray.Add(T? value).

This adds an item of arbitrary type to the array, possibly invoking the serializer to convert to a JsonNode. As such, this might require reflection. Because the serializer might be required, calling this method will generate AOT warnings.

Now, you think you are calling the first method, but the value you are passing is not declared to be of type JsonNode -- it's declared to be JsonObject, a derived type of JsonNode. Thus the compiler seems to be choosing the second overload and subsequently emitting the warning even though in practice the JsonObject will get added without any conversion or serialization.

So, how can you avoid the annoying warning?

Firstly, you could manually cast your deviceEntry to a JsonNode thereby explicitly calling the first overload:

deviceEntries.Add((JsonNode)deviceEntry);

Secondly, you could use LINQ to create an array of nodes then invoke the new JsonArray(JsonNode []) constructor which also does not generate any AOT warnings:

var deviceEntries = new JsonArray(deviceIds.Select( deviceId => { var deviceEntry = new JsonObject { ["deviceId"] = deviceId }; // more properties to be added to deviceEntry object depending on how it goes return deviceEntry; }).ToArray());

dbc's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Read Entire Article