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?

7
  • Do you really need to make a double json string? Commented Jul 6, 2021 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); Commented Jul 6, 2021 at 11:46
  • @DavidG - Thanks David! Yep! I should have though about this.Works fine. Commented Jul 6, 2021 at 11:53
  • @DavidG - My solution to sort doesn`t work when the string & number combination is more than 5 chars. Could you help? Commented Jul 6, 2021 at 14:44
  • Not sure what you mean. Sorting is sorting, it has nothing to do with how long the fields are. Commented Jul 6, 2021 at 15:21

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.