Search code examples
c#jsonwebresponse

Sorting Json data


I hate some trouble sorting the data I recieve from a webresponse.

Right now they come in "random", and I haven't been able to sort it at all.

Right now the partial class looks like this:

namespace computers{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
using J = Newtonsoft.Json.JsonPropertyAttribute;
public partial class GettingStarted
{
    [J("devices")] public Device[] Devices { get; set; }
}

public partial class Device
{
    [J("device_id")] public string DeviceId { get; set; }
    [J("assigned_to")] public bool AssignedTo { get; set; }
    [J("alias")] public string Alias { get; set; }
    [J("description")] public string Description { get; set; }
    [J("last_seen")] public string LastSeen { get; set; }
    [J("remotecontrol_id")] public string RemotecontrolId { get; set; }
    [J("groupid")] public string Groupid { get; set; }
    [J("online_state")] public string OnlineState { get; set; }
    [J("supported_features")] public string SupportedFeatures { get; set; }
}

public partial class GettingStarted
{
    public static GettingStarted FromJson(string json) => JsonConvert.DeserializeObject<GettingStarted>(json, Converter.Settings);
}

public static class Serialize
{
    public static string ToJson(this GettingStarted self) => JsonConvert.SerializeObject(self, Converter.Settings);
}

public class Converter
{
    public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
    {
        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
        DateParseHandling = DateParseHandling.None,
    };
}

As said before, the data comes in random and all my attempts at sorting them result in either a crash or does nothing.

Thanks in advance!


Solution

  • You can use lambda expressions to achieve this

    Add using System.Linq directive

    After you pupulate your 'Devices' array, use this to sort it:

    Devices = Devices.OrderBy(x=>x.Alias).ToArray()