[英]How to get string value of key from nested JSON object?
JSON:
{
event_name: 'request_queue_items',
event_data: {
amount: 20
},
}
事件处理程序:
private void OnMessage(string message)
{
if (!message.Contains("{") || !message.Contains("}"))
{
return; // It's not JSON, we don't care...
}
var jsonObject = (JObject)JsonConvert.DeserializeObject(message);
var eventName = jsonObject["event_name"].Value<string>();
var eventData = jsonObject["event_data"].Value<string>();
Console.WriteLine("RECEIVED: " + eventName);
Console.WriteLine("WITH DATA: " + eventData);
Console.WriteLine();
Console.WriteLine();
}
错误消息: Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken
堆栈跟踪:
12/12/2020 15:19:07 [Error] Application Error System.InvalidCastException: Cannot cast Newtonsoft.Json.Linq.JObject to Newtonsoft.Json.Linq.JToken.
at Newtonsoft.Json.Linq.Extensions.Convert[T,U](T token)
at Newtonsoft.Json.Linq.Extensions.Value[T,U](IEnumerable`1 value)
at Newtonsoft.Json.Linq.Extensions.Value[U](IEnumerable`1 value)
您可以执行以下操作。 使用 JObject.Parse 并使用 JObject 而不是字符串。 您仍然可以使用.ToString() 将内部 json 作为字符串获取:
if (!message.Contains("{") || !message.Contains("}"))
{
return; // It's not JSON, we don't care...
}
var jsonObject = JObject.Parse(message); // use JObject
var eventName = jsonObject["event_name"].Value<string>();
var eventData = jsonObject["event_data"].Value<JObject>(); //use JObject as it is not a string
Console.WriteLine("RECEIVED: " + eventName);
Console.WriteLine("WITH DATA: " + eventData);
Console.WriteLine();
eventData.ToString() 的值将是:
event_data: {
amount: 20
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.