我从 Postman 那里发送了一个请求,它在后端遇到了API。方法的返回类型是JObject。我使用JObject.Parse方法解析字符串。结果得到了一个空数组。注意:NewtonSoft(到版本10)更新已被发布。
// 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 的响应显示一个空数组。postman response
我还在GetCustom方法中尝试了以下代码,但这些代码也返回空值。
案例:1
dynamic resultObject = new ExpandoObject();
resultObject.somefield = "somevalue";
resultObject.someotherfield = 1995;
return Json(new { status = "success", result = resultObject });
** Package 箱: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;
** Package 箱: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;
** Package 箱:4**
var json = @"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
var o = (JObject)JToken.FromObject(json);
return o;
我正在尝试将第三方API返回的对象序列化为JSON,但我无法控制第三方API或其返回的对象。
2条答案
按热度按时间omhiaaxx1#
我找到了一个解决方案,我使用HttpResponseMessage来代替返回JObject,将JObject序列化为字符串,并返回为HttpResponseMessage,类型为application/json。
7eumitmz2#
尝试使用JsonConvert.SerializeObject(结果)。