简体   繁体   English

对来自 web api 的 JSON 响应进行排序

[英]Sort JSON response from web api

I want to sort my JSON response by calling web API and will use only the highest probability and tagName from the response API.我想通过调用 Web API 对我的 JSON 响应进行排序,并且只使用响应 API 中的最高概率和 tagName。

How can I do this in C# or do I need to use any lib?如何在 C# 中执行此操作,还是需要使用任何库? 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我的程序过程是将图像数据发送到网络并接收 JSON 数据响应

{
  "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.为了对 JSON 进行排序,最好先将其反序列化为 .NET 对象,然后使用 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.如果您需要带有排序内容的 JSON,您可以在之后对其进行序列化。 The first step is to define classes that mimic the structure of your JSON.第一步是定义模仿 JSON 结构的类。 You can do this easily in Visual Studio using Edit -> Paste special -> Paste JSON as classes .您可以在 Visual Studio 中使用Edit -> Paste special -> Paste JSON as classes轻松完成此操作。

After that, you can deserialize your JSON string to objects.之后,您可以将 JSON 字符串反序列化为对象。 There are various frameworks that help you in this regard, the most famous ones being the follwing:在这方面有各种框架可以帮助您,最著名的是以下框架:

  • System.Text.Json is a JSON (de)serializer contained in the .NET framework, so you don't need extra components if you are already using .NET (available from .NET Core version 3). System.Text.Json 是包含在 .NET 框架中的 JSON(反)序列化程序,因此如果您已经在使用 .NET(可从 .NET Core 版本 3 获得),则不需要额外的组件。
  • JSON.NET aka Newtonsoft.Json that is also available for the classic .NET Framework, eg .NET Framework 4.7 and lower. JSON.NET aka Newtonsoft.Json 也可用于经典.NET Framework,例如 .NET Framework 4.7 及更低版本。

In the following sample, I have created the classes myself (Paste special creates lowercase property names that conflict with the .NET naming convention):在以下示例中,我自己创建了类(Paste special 创建与 .NET 命名约定冲突的小写属性名称):

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:之后,我将您的 JSON 存储在一个字符串中(但您可以使用从 POST 收到的字符串)并使用 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.因此,小写 JSON 属性名称正确映射到 .NET 类中的大写属性名称。

The predictions can easily be sorted using the Linq methods OrderByDescending and ThenBy :可以使用 Linq 方法OrderByDescendingThenBy轻松对预测进行排序:

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:要将对象结构再次序列化为 JSON,可以使用此方法:

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.如果您没有大量数据,则此方法将起作用,如果您处理 Web 请求的结果,通常情况并非如此。

See this fiddle to check the sample.请参阅此小提琴以检查示例。

You can find an overview over System.Net.Json here .您可以在此处找到 System.Net.Json 的概述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM