I want to sort my JSON response by calling web API and will use only the highest probability and tagName from the response API.
How can I do this in C# or do I need to use any lib? EDIT: This is the code that use to call I'm very new to coding thank you for every response. My program procedure is to send image data to web and receive the JSON data response
{
"predictions": [
{
"**probability**": 0.15588212,
"tagId": "5ac049bf-b01e-4dc7-b613-920c75579c41",
"**tagName**": "DH246F",
"boundingBox": {
"left": 0.4654134,
"top": 0.52319163,
"width": 0.16658843,
"height": 0.20959526
}
},
{
"probability": 0.11000415,
"tagId": "5ac049bf-b01e-4dc7-b613-920c75579c41",
"tagName": "DH246F",
"boundingBox": {
"left": 0.0,
"top": 0.18623778,
"width": 0.31140158,
"height": 0.81376123
}
}
]
}
using System;
using System.Net.Http.Headers;
using System.Text;
using System.Net.Http;
using System.Web;
using System.IO;
namespace Rest_API_Test
{
static class Program
{
static void Main(string[] args)
{
string imageFilePath = @"C:\Users\wissarut.s\Desktop\Test Capture\Left.png";
MakeRequest(imageFilePath);
Console.ReadLine();
}
public static async void MakeRequest(string imageFilePath)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Prediction-key", "****");
var uri = "*******************";
HttpResponseMessage response;
byte[] byteData = GetBytesFromImage(imageFilePath);
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
response = await client.PostAsync(uri, content);
Console.WriteLine(await response.Content.ReadAsStringAsync());
Console.WriteLine("From Left Side Camera");
}
}
public static byte[] GetBytesFromImage(string imageFilePath)
{
FileStream fs = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
BinaryReader binReader = new BinaryReader(fs);
return binReader.ReadBytes((int)fs.Length);
}
}
}
In order to sort the JSON, it is best to first deserialize it to .NET objects and sort it using Linq. After the deserialization, you have the contents in memory and you can handle better. If you need a JSON with the sorted content, you can serialize it afterwards. The first step is to define classes that mimic the structure of your JSON. You can do this easily in Visual Studio using Edit -> Paste special -> Paste JSON as classes.
After that, you can deserialize your JSON string to objects. There are various frameworks that help you in this regard, the most famous ones being the follwing:
In the following sample, I have created the classes myself (Paste special creates lowercase property names that conflict with the .NET naming convention):
public class Container
{
public IEnumerable<Prediction> Predictions { get; set; }
}
public class Prediction
{
public decimal Probability { get; set; }
public Guid TagId { get; set; }
public string TagName { get; set; }
public BoundingBox BoundingBox { get; set; }
}
public class BoundingBox
{
public decimal Left { get; set; }
public decimal Top { get; set; }
public decimal Width { get; set; }
public decimal Height { get; set; }
}
After that, I stored your JSON in a string (but you can use the string you receive from the POST) and deserialized it in a object structure using System.Text.Json:
var options = new JsonSerializerOptions()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
};
var container = JsonSerializer.Deserialize<Container>(json, options);
Above code configures the options so that camel-casing is applied for property names when reading. So the lowercase JSON property names are mapped to the uppercase property names in the .NET classes correctly.
The predictions can easily be sorted using the Linq methods OrderByDescending
and ThenBy
:
container.Predictions = container.Predictions
.OrderByDescending(x => x.Probability)
.ThenBy(x => x.TagName);
The result is the following order:
0.15588212, DH246F, 5ac049bf-b01e-4dc7-b613-920c75579c41
0.11000415, DH246F, 5ac049bf-b01e-4dc7-b613-920c75579c41
To serialize the object structure to JSON again, you can use this method:
var serialized = JsonSerializer.Serialize(container, options);
This approach will work if you do not have huge amounts of data which typically is not the case if you handle the result of a web request.
See this fiddle to check the sample.
You can find an overview over System.Net.Json here.