【问题标题】:JSON return empty Array in JObject return typeJSON在JObject返回类型中返回空数组
【发布时间】:2021-02-14 19:23:36
【问题描述】:

我从邮递员那里发送了一个请求,它访问了后端的 API。 该方法的返回类型是 JObject 。 我正在使用 JObject.Parse 方法解析字符串。 结果是得到一个空数组。 注意:对 newtonsoft(到版本 10)的更新是 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();
        }
}

此方法返回一个 JObject,但邮递员的响应显示一个空数组。 postman response

我还在 GetCustom 方法中尝试了以下代码,但这些代码也返回空。

案例:1

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

案例: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;

案例: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;

案例:4

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

我正在尝试将第三方 API 返回的对象序列化为 JSON。我无法控制第三方 API 或其返回的对象。

【问题讨论】:

标签: c# arrays json json.net


【解决方案1】:

我找到了一种解决方案,那就是, 而是返回 JObject 我使用了 HttpResponseMessage。将 JObject 序列化为字符串,并作为类型 = application/json 的 HttpResponseMessage 返回。

public HttpResponseMessage GetCustom(int appId)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-15
    • 2022-07-26
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    相关资源
    最近更新 更多