4

I have a JSON file from our CRM:

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

Now I need to sort this JSON by 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));
DennisM
  • 17
  • 7
Francis
  • 343
  • 2
  • 5
  • 16
  • When you say `load my JSON file into the method from the solution`, you mean [embedded resource](https://msdn.microsoft.com/en-us/library/e2c9s1d7%28v=vs.100%29.aspx?f=255&MSPPError=-2147217396)? – Bob Sep 09 '16 at 09:28
  • No, sorry. I mean that I don`t know how to load my file into the code from the solution... – Francis Sep 09 '16 at 09:30

1 Answers1

4

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 AscMyJson(string json)
{
    var listOb = JsonConvert.DeserializeObject<List<RootObject>>(json);
    var descListOb = listOb.OrderBy(x => x.id);
    return JsonConvert.SerializeObject(descListOb);
}
Bob
  • 545
  • 3
  • 8
M. Wiśnicki
  • 6,094
  • 3
  • 23
  • 28
  • OP wants it ascending use `OrderBy` instead of `OrderByDescending` – Bob Sep 09 '16 at 09:36
  • Looks great, but now the order is wrong. How can we switch the order? At the moment, the ID which should be the last is on top of the file :) – Francis Sep 09 '16 at 09:37
  • 1
    Got it - var listOb = JsonConvert.DeserializeObject>(json); var descListOb = listOb.OrderBy(x => x.id); return JsonConvert.SerializeObject(descListOb); – Francis Sep 09 '16 at 09:38