访问嵌套的键值对
本文关键字:键值对 嵌套 访问 | 更新日期: 2023-09-27 18:15:25
对于下面的数据,我有一个相对简单的嵌套JSON字符串:
{ "d" : {
"humidity": "39.21",
"acc_y": "1.21",
"ambient_temp": "24.21",
"air_pressure": "1029.21",
"object_temp": "23.21",
"acc_z": "0.21",
"acc_x": "3.21",
}
}
我有一个c# windows服务应用程序,它接收JSON字符串和反序列化字符串。
private static void client_MqttMsgPublishReceived(object sender, uPLibrary.Networking.M2Mqtt.Messages.MqttMsgPublishEventArgs e)
{
//Console.WriteLine(System.Text.Encoding.Default.GetString(e.Message));
string json = System.Text.Encoding.Default.GetString(e.Message);
var obj = JsonConvert.DeserializeObject<IDictionary<string, object>>(json, new JsonConverter[] { new MyConverter() });
}
我有一个Myconvert类,看起来像这样,它读取JSON:
class MyConverter : CustomCreationConverter<IDictionary<string, object>>
{
public override IDictionary<string, object> Create(Type objectType)
{
return new Dictionary<string, object>();
}
public override bool CanConvert(Type objectType)
{
// in addition to handling IDictionary<string, object>
// we want to handle the deserialization of dict value
// which is of type object
return objectType == typeof(object) || base.CanConvert(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartObject
|| reader.TokenType == JsonToken.Null)
return base.ReadJson(reader, objectType, existingValue, serializer);
// if the next token is not an object
// then fall back on standard deserializer (strings, numbers etc.)
return serializer.Deserialize(reader);
}
}
我可以在obj对象的调试窗口中看到JSON数据。
这可能是一个非常直接的问题,我如何提取JSON键值对数据(例如。湿度,环境温度)在我的程序中使用,因为目前我只能在调试窗口中看到它们?
谢谢你的帮助!
您实际上不需要转换器来反序列化此JSON。一个简单的包装器类就可以做到:
class Wrapper
{
public Dictionary<string, object> d { get; set; }
}
:
Dictionary<string, object> obj = JsonConvert.DeserializeObject<Wrapper>(json).d;
小提琴:https://dotnetfiddle.net/vnoQxi