/// <summary> /// Read the <see cref="HttpContent"/> as OData resource set. /// </summary> /// <param name="content">The http content.</param> /// <returns>The OData array.</returns> public static async Task <ODataArray> ReadAsODataArrayAsync(this HttpContent content) { if (content == null) { throw new ArgumentNullException(nameof(content)); } Stream stream = await content.ReadAsStreamAsync(); using (JsonDocument doc = await JsonDocument.ParseAsync(stream)) { JsonElement root = doc.RootElement; // OData array is an object as: // { // "@odata.context":... // "value" [ ... ] // } if (root.ValueKind != JsonValueKind.Object) { return(null); } if (!root.TryGetProperty("value", out JsonElement value) && value.ValueKind != JsonValueKind.Array) { return(null); } ODataArray odataArray = new ODataArray(); // value array foreach (var item in value.EnumerateArray()) { IODataValue itemValue = item.ParseAsODataValue(); odataArray.Add(itemValue); } // context uri odataArray.ContextUri = ReadStringPropertyValue(root, "@odata.context", "@context"); // next link odataArray.NextLink = ReadStringPropertyValue(root, "@odata.nextlink", "@nextlink"); // odata.count odataArray.TotalCount = ReadIntPropertyValue(root, "@odata.count", "@count"); return(odataArray); } }
/// <summary> /// Read <see cref="JsonElement"/> as OData value. /// </summary> /// <param name="node">The JSON element.</param> /// <returns>The OData value.</returns> public static IODataValue ParseAsODataValue(this JsonElement node) { switch (node.ValueKind) { case JsonValueKind.Object: // A JSON object. ODataObject odataObject = new ODataObject(); foreach (JsonProperty property in node.EnumerateObject()) { odataObject[property.Name] = ParseAsODataValue(property.Value); } return(odataObject); case JsonValueKind.Array: // A JSON array. ODataArray odataArray = new ODataArray(); foreach (JsonElement element in node.EnumerateArray()) { odataArray.Add(ParseAsODataValue(element)); } return(odataArray); case JsonValueKind.String: // A JSON string. return(new ODataString(node.GetString())); case JsonValueKind.Number: // A JSON number. return(ReadNumber(node)); case JsonValueKind.True: // A JSON true. return(ODataBoolean.True); case JsonValueKind.False: // A JSON false. return(ODataBoolean.False); case JsonValueKind.Null: // A JSON null. return(ODataNull.Null); case JsonValueKind.Undefined: default: throw new ODataException($"Found an Undefined JSON element '{node.GetRawText()}'!"); } }