Search code examples
c#arraysjsonjson.net

JSON return empty Array in JObject return type


I was sending a request from the postman and it hits the API in the backend. The return type of the method is JObject . I am parsing the string using JObject.Parse method. The result is getting an empty array. Note : an update to newtonsoft(to version 10) is haapend.

// GET /test/custom
[System.Web.Http.ActionName("custom")]
public JObject GetCustom(int Id)
{
        try
        {
         string json = @"{
                  CPU: 'Intel',
                   Drives: [
                    'DVD read/writer',
                    '500 gigabyte hard drive'
                     ]
                     }";
                JObject rtn = JObject.Parse(json);
                return rtn;
                }
        }
        catch (Exception ex)
        {
         return new JObject();
        }
}

this method returns a JObject, but the response from the postman showing an empty array. postman response

I also tried the following piece of codes inside the GetCustom method, but these also return empty.

Case:1

dynamic resultObject = new ExpandoObject();
            resultObject.somefield = "somevalue";
            resultObject.someotherfield = 1995;
            return Json(new { status = "success", result = resultObject });

Case:2

var jObject = new JObject();
            jObject.Add("someField", "someValue");
            jObject.Add("otherField", 1995);
            var newObj = new { status = "success", result = jObject };
            var returnThis = JsonConvert.SerializeObject(newObj);
            var root = JObject.FromObject(new { sectionData = returnThis });
            return root;

Case:3

var cycleJson = JObject.Parse(@"{""name"":""john""}");
            //add surname
            cycleJson["surname"] = "doe";
            //add a complex object
            cycleJson["complexObj"] = JObject.FromObject(new { id = 1, name = "test" });
            return cycleJson;

Case:4

var json = @"{
              CPU: 'Intel',
              Drives: [
                'DVD read/writer',
                '500 gigabyte hard drive'
              ]
            }";
            var o = (JObject)JToken.FromObject(json);
            return o;

I'm trying to serialize an object returned by a third party API into JSON. I don't have any control over the third party API or the object it returns.


Solution

  • I found out one solution and which is, instead returnng JObject I used HttpResponseMessage. Serialised JObject into string and returned as HttpResponseMessage with type = application/json.

    public HttpResponseMessage GetCustom(int appId)
    
    var appCustom=JsonConvert.SerializeObject(json);
                return new HttpResponseMessage()
                {
                    Content = new StringContent(appCustom, System.Text.Encoding.UTF8, "application/json")
                };