Search code examples
c#jsonjson.net

Using Newtonsoft.JSON (JSON.net), how do I add a JArray, with child JObjects to an existing JObject


This is a C# application using the Newtonsoft.JSON library.

I have a JObject that is a search, to which I need to add a JArray, to which I need to add some more JObjects

This is what I need to add to my search object:

"sort": [
  {
    "_score": {
      "order": "asc"
    }
  }
]

I am trying to follow the example HERE

I have tried this:

JProperty orderProperty = new JProperty("order","asc");
JObject scoreObject = new JObject("_score", orderProperty);
search.Add("sort", new JArray { new JObject { scoreObject } });

But this does not work, and I get this error:

An unhandled exception has occurred while executing the request. System.ArgumentException: Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.

This is a method that almost worked, but the JSON didn't come out correctly:

JProperty orderProperty = new JProperty("order","asc");
JObject scoreObject = new JObject();
scoreObject.Add(orderProperty);
search.Add("sort", new JArray { "_score", scoreObject });

And the JSON came out looking like this:

"sort":[
    "_score",{
        "order":"asc"
    }
],

EDIT:

I also tried this, but it came out with the same error:

search.Add("sort",new JArray {
    new JObject {
        new JObject {
            "_score", new JProperty("order", "asc")
        }
    } 
});

Solution

  • Create the inner JObject with the property order.

    Create the outer JObject with the property _score, which contains the inner JObject.

    Create a JArray and add the outer JObject to it.

    Add this JArray to your existing search JObject under the key sort.

    JObject orderObject = new JObject();
    orderObject.Add("order", "asc");
    
    JObject scoreObject = new JObject();
    scoreObject.Add("_score", orderObject);
    
    JArray sortArray = new JArray();
    sortArray.Add(scoreObject);
    
    search.Add("sort", sortArray);