0

How to add sorted json('sortedJson') back to the whole json('jObj') below? Or is there an alternative to do the below?

 Json:
        {
          "Information": [
            {
              "FieldName": "Area04",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area02",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area01",
              "Draft": "Unknown",
            },
            {
              "FieldName": "Area03",
              "Draft": "Unknown",
            }
          ],
          "OtherInfo": []
        }


    Code:     
        static void Main(string[] args)
          {
            string _json = "{'Information': [{'FieldName': 'Area04','Draft': 'Unknown'},{'FieldName': 'Area02','Draft': 'Unknown'},{'FieldName': 'Area01','Draft': 'Unknown'},{'FieldName': 'Area03','Draft': 'Unknown'}],'OtherInfo': []}";
            var jObj = JsonConvert.DeserializeObject<Informat>(_json);
            var test1 = jObj.Information.OrderBy(x => x.FieldName);
            var sortedJson = JsonConvert.SerializeObject(test1);
           //Add code to merge 'sortedJson' to '_json'
          }
    
    Class:
    public class Informat
    {
        public Information[] Information { get; set; }
        public object[] OtherInfo { get; set; }
    }
    
    public class Information
    {
        public string FieldName { get; set; }
        public string Draft { get; set; }
    }

I dont know how to add the sorted json back to whole json. Could you please help me with this?

DeSon
  • 147
  • 13
  • Do you really need to make a double json string? – Serge Jul 06 '21 at 11:44
  • 1
    Just set the ordered output back into your class and deserialise the entire object back to JSON. So `jObj.Information = test1.ToArray(); _json = JsonConvert.SerializeObject(jObj);` – DavidG Jul 06 '21 at 11:46
  • @DavidG - Thanks David! Yep! I should have though about this.Works fine. – DeSon Jul 06 '21 at 11:53
  • @DavidG - My solution to sort doesn`t work when the string & number combination is more than 5 chars. Could you help? – DeSon Jul 06 '21 at 14:44
  • Not sure what you mean. Sorting is sorting, it has nothing to do with how long the fields are. – DavidG Jul 06 '21 at 15:21
  • @DavidG - If you look at the 'FieldName', it is a combination of char & digits, when field names are like - 'Area103' & 'Area03' it will not recognize numbers and sorting fails. – DeSon Jul 06 '21 at 15:23
  • Ah, well that's a different question to ask. Plenty of other duplicates will help though. For example https://stackoverflow.com/questions/9988937/sort-string-numbers – DavidG Jul 06 '21 at 15:34

1 Answers1

2

Here's an example using Array.Sort()

var jObj = JsonConvert.DeserializeObject<Informat>(_json);
Array.Sort(jObj.Information, (x, y) => x.FieldName.CompareTo(y.FieldName));
var sortedJson = JsonConvert.SerializeObject(jObj);
oRoiDev
  • 339
  • 1
  • 8