Francis Francis - 2 months ago 14
JSON Question

C# sort JSON for value

I have a JSON file form our CRM:

[{"name": "erwin", "type":"ma", "id":"129"}, {"name": "hans", "type":"tf", "id":"12"}]


Now I nedd to sort this JSON by the ID value, in my example the output should be:

[{"name": "hans", "type":"tf", "id":"12"}, {"name": "erwin", "type":"ma", "id":"129"}]


I already found this thread: C# Sort JSON string keys

But I don`t know how to load my JSON file into the method from the solution.
Maybe with json.net?
Regards,

Francis

EDIT:

string sourcePath = @Settings.Default.folder;
string pathToSourceFile = Path.Combine(sourcePath, "myfile.json");
var list = JsonConvert.DeserializeObject<List<Gesamtplan>>(File.ReadAllText(pathToSourceFile));

Answer

Try like this

using Newtonsoft.Json;

    public class RootObject
    {
        public string name { get; set; }
        public string type { get; set; }
        public string id { get; set; }
    }

    private string DescMyJson(string json)
    {
        var listOb = JsonConvert.DeserializeObject<List<RootObject>>(json);
        var descListOb = listOb.OrderByDescending(x => x.id);
        return JsonConvert.SerializeObject(descListOb);
    }
Comments