如何解决无法将 ServerEventMessage 从 ServiceStack 解析为 C#
我能够获得第一级 JSON,但不能获得第二级。
我从这里获取 JSON -
var client = new ServerEventsClient(baseUri) {
OnMessage = e => analysedata(e),}.Start();
在这个函数中,我试图解析 -
public string analysedata(ServerEventMessage test)
{
var parsed = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(test));
string p1 = parsed["Data"].Value<string>();
}
现在 p1 应该是一个字符串?但它是类型 - Newtonsoft.Json.Linq.JValue
parsed["Data"] 是我的服务器发送的 JSON 响应。
如果我执行 parsed["Data"]["event_id"]
Debug.Writeline 不会在输出中打印任何内容。
文档 - https://docs.servicestack.net/csharp-server-events-client#assigning-callback-handlers
解决方法
关于JObject的使用,你可以查看下面的代码。我使用了一个 JSON 字符串作为参考。
string json = @"{
'channel': {
'title': 'James Newton-King','link': 'http://james.newtonking.com','description': 'James Newton-King\'s blog.','item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex','description': 'Announcing the release of Json.NET 1.3,the MIT license and the source on CodePlex','link': 'http://james.newtonking.com/projects/json-net.aspx','categories': [
'Json.NET','CodePlex'
]
},{
'title': 'LINQ to JSON beta','description': 'Announcing LINQ to JSON','LINQ'
]
}
]
}
}";
JObject rss = JObject.Parse(json);
string rssTitle = (string)rss["channel"]["title"];
// James Newton-King
string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET","CodePlex"]
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex
,
使用JObject.Parse
解析json
public string analysedata(ServerEventMessage test)
{
var parsed = JObject.Parse(test.Json));
string p1 = parsed["Data"].Value<string>();
}
,
由于您已经在使用 ServiceStack,因此推荐使用其 JS Utils 来解析任意 json,例如:
const config = require("config");
const jwt = require("jsonwebtoken");
function auth(res,req,next) {
const token = req.header("x-auth-token");
// Check for token
if (!token) res.status(401).json({ msg: "No token,authorization denied" });
try {
// verify token
const decoded = jwt.verify(token,config.get("jwtSecret"));
// Add user from payload
req.user = decoded;
next();
} catch (e) {
res.status(400).json({ msg: "Token is not valid" });
}
}
module.exports = auth;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。